Mex
Time Limit: 15000/5000 MS (Java/Others) Memory Limit: 65535/65535 K (Java/Others)Total Submission(s): 3615 Accepted Submission(s): 1209
Problem Description
Mex is a function on a set of integers, which is universally used for impartial game theorem. For a non-negative integer set S, mex(S) is defined as the least non-negative integer which is not appeared in S. Now our problem is about mex function on a sequence.
Consider a sequence of non-negative integers {ai}, we define mex(L,R) as the least non-negative integer which is not appeared in the continuous subsequence from aL to aR, inclusive. Now we want to calculate the sum of mex(L,R) for all 1 <= L <= R <= n.
Consider a sequence of non-negative integers {ai}, we define mex(L,R) as the least non-negative integer which is not appeared in the continuous subsequence from aL to aR, inclusive. Now we want to calculate the sum of mex(L,R) for all 1 <= L <= R <= n.
Input
The input contains at most 20 test cases.
For each test case, the first line contains one integer n, denoting the length of sequence.
The next line contains n non-integers separated by space, denoting the sequence.
(1 <= n <= 200000, 0 <= ai <= 10^9)
The input ends with n = 0.
For each test case, the first line contains one integer n, denoting the length of sequence.
The next line contains n non-integers separated by space, denoting the sequence.
(1 <= n <= 200000, 0 <= ai <= 10^9)
The input ends with n = 0.
Output
For each test case, output one line containing a integer denoting the answer.
Sample Input
3 0 1 3 5 1 0 2 0 1 0
Sample Output
5 24HintFor the first test case: mex(1,1)=1, mex(1,2)=2, mex(1,3)=2, mex(2,2)=0, mex(2,3)=0,mex(3,3)=0. 1 + 2 + 2 + 0 +0 +0 = 5.
#include<iostream>
#include<cmath>
#include<cstdio>
#include<cstdlib>
#include<string>
#include<cstring>
#include<algorithm>
#include<vector>
#include<map>
#include<set>
#include<stack>
#include<list>
#include<queue>
#include<ctime>
#define eps 1e-6
#define INF 0x3fffffff
#define PI acos(-1.0)
#define ll __int64
#define lson l,m,(rt<<1)
#define rson m+1,r,(rt<<1)|1
#pragma comment(linker, "/STACK:1024000000,1024000000")
using namespace std;
#define Maxn 210000
int sa[Maxn],pos[Maxn],full[Maxn];
int main()
{
//freopen("in.txt","r",stdin);
//freopen("out.txt","w",stdout);
int n;
while(scanf("%d",&n)&&n)
{
for(int i=1;i<=n;i++)
scanf("%d",&sa[i]);
memset(pos,0,sizeof(pos));
memset(full,0,sizeof(full));
int last;
ll tt=0,ans=0;
for(int i=1;i<=n;i++)
{
if(sa[i]<n)//
{
last=pos[sa[i]];//前一个sa[i]的最晚位置
pos[sa[i]]=i; //最晚位置
for(int j=sa[i];j<n;j++)
{
if(j) //考虑j对前面区间的影响
full[j]=min(full[j-1],pos[j]); //
else
full[j]=i;
if(full[j]>last)
tt+=full[j]-last; //last+1到full[j]区间内所有点到i的值+1,逐次累加
else
break;
}
}
printf("i:%d %I64d\n",i,tt);
ans+=tt;
}
printf("%I64d\n",ans);
}
return 0;
}