Mex
Time Limit: 15000/5000 MS (Java/Others) Memory Limit: 65535/65535 K (Java/Others)
Total Submission(s): 4458 Accepted Submission(s): 1460
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.
定义mex(L,R)是指在L~R范围内未出现过的最小的非负整数,题目中要求计算 1 <= L <= R <= n 内所有的mex之和;
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.
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
24
Hint
For 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.
Source
2013 ACM/ICPC Asia Regional Hangzhou Online
Recommend
liuyiding
思路:区间问题啊,线段树啊,什么线段树?!!!我不想写啊,算了吧算了吧
我可不可以递推写啊,好像可以。
因为只有n个数,只要数字大于n 的话我就可以想是不是未出现的最小非负整数为0 呢
我还需要知道什么?我还需要知道的是这个数字上一次是在哪里出现的,
优雅的暴力枚举(怎么可能优雅,不要玷污优雅这个词了)?具体的看代码吧:
#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int Max=200010;
int a[Max],mex[Max],pre[Max];
int main(){
int n;
while(cin>>n&&n){
fill(mex,mex+Max,0);
fill(pre,pre+Max,0);
for(int i=1;i<=n;i++) cin>>a[i];
ll add=0,ans=0;
for(int i=1;i<=n;i++){
if(a[i]<n){
ll t=pre[a[i]];
pre[a[i]]=i;
for(int j=a[i];j<=n;j++){
mex[j]=j==0?pre[j]:min(mex[j-1],pre[j]);
if(mex[j]>t) add+=mex[j]-t;
else break;
}
}
ans+=add;
}
cout<<ans<<endl;
}
}