Codeforces 862A Mahmoud and Ehab and the MEX
传送门:CF-862A
Dr. Evil kidnapped Mahmoud and Ehab in the evil land because of their performance in the Evil Olympiad in Informatics (EOI). He decided to give them some problems to let them go.
Dr. Evil is interested in sets, He has a set of n integers. Dr. Evil calls a set of integers evil if the MEX of it is exactly x. the MEX of a set of integers is the minimum non-negative integer that doesn't exist in it. For example, the MEX of the set {0, 2, 4} is 1 and the MEX of the set {1, 2, 3} is 0 .
Dr. Evil is going to make his set evil. To do this he can perform some operations. During each operation he can add some non-negative integer to his set or erase some element from it. What is the minimal number of operations Dr. Evil has to perform to make his set evil?
The first line contains two integers n and x (1 ≤ n ≤ 100, 0 ≤ x ≤ 100) — the size of the set Dr. Evil owns, and the desired MEX.
The second line contains n distinct non-negative integers not exceeding 100 that represent the set.
The only line should contain one integer — the minimal number of operations Dr. Evil should perform.
5 3
0 4 5 6 7
2
1 0
0
1
5 0
1 2 3 4 5
0
For the first test case Dr. Evil should add 1 and 2 to the set performing 2 operations.
For the second test case Dr. Evil should erase 0 from the set. After that, the set becomes empty, so the MEX of it is 0.
In the third test case the set is already evil.
思路:先排序,然后求Mex。与x进行比较,如果mex=x,输出0;如果mex>x,直接去掉x,所以输出1;mex<x时,向数列中填数直到mex>x或者mex=0,输出操作的次数。需要注意的是,如果数位不足,mex的最大值依然小于x,需要额外判断。
1 #include<iostream> 2 using namespace std; 3 4 int main() 5 { 6 int k; 7 int re; 8 int rec; 9 int mex; 10 int temp; 11 int n,x; 12 int a[110]; 13 cin>>n>>x; 14 for (int i=0; i<n; i++) cin>>a[i]; 15 for (int i=0; i<n; i++) 16 { 17 for (int j=i+1; j<n; j++) 18 { 19 if (a[i]>a[j]) 20 { 21 temp=a[i]; 22 a[i]=a[j]; 23 a[j]=temp; 24 } 25 } 26 } 27 28 mex=a[n-1]+1; 29 re=n-1; 30 for(int i=0; i<n; i++) 31 { 32 if (a[i]!=i) 33 { 34 mex=i; 35 re=i-1; 36 break; 37 } 38 } 39 40 if (mex==x) cout<<0; 41 else if (mex>x) cout<<1; 42 else 43 { 44 rec=0; 45 while(mex<x&&mex!=a[n-1]+1) 46 { 47 rec++; 48 int q=mex+1; 49 re++; 50 k=re; 51 re=n-1; 52 mex=a[n-1]+1; 53 for(int i=k;i<n;i++) 54 { 55 if(a[i]!=q) 56 { 57 re=i-1; 58 mex=q; 59 break; 60 } 61 q++; 62 } 63 } 64 if(mex==x) cout<<rec; 65 else if(mex>x) cout<<rec+1; 66 else cout<<(x-mex)+rec; 67 } 68 69 return 0; 70 }