fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int main() {
  5.  
  6. //we have to find the maximum lexicographic mex first come sthe
  7. //greater element
  8. //if both are qual then come s the size
  9.  
  10.  
  11. ///first we have to precompute the suffix me xfor each element so that we can
  12. //do the proplem properly
  13.  
  14. int n;
  15. cin>>n;
  16.  
  17. vector<int>nums(n);
  18.  
  19. for(int i=0;i<n;i++){
  20. cin>>nums[i];
  21. }
  22. vector<bool>seen(n+1,false);
  23. vector<int>suff(n);
  24. int cur=0;
  25. for(int i=n-1;i>=0;i--){
  26.  
  27. if(nums[i]<=n)seen[nums[i]]=true;
  28.  
  29. while(seen[cur]){
  30. cur++;
  31. }
  32.  
  33. suff[i]=cur;
  34. }
  35.  
  36. vector<int>ans;
  37. //now e ahev to move from the front of the arary calculating
  38. //like first max is suff[0] and we have to find the lasrgest val where it apperas like suff[0]
  39.  
  40. int i=0;
  41. vector<int>found(n+1,0);
  42. int timer=1;
  43. while(i<n){
  44. int maxi=suff[i];
  45.  
  46. int cur=0;
  47. while(i<n&&cur!=maxi){
  48. if(nums[i]<=n)found[nums[i]]=timer;
  49.  
  50. while(found[cur]==timer){
  51. cur++;
  52. }
  53. i++;
  54. }
  55. timer++;
  56. ans.push_back(maxi);
  57. }
  58.  
  59. for(int i=0;i<ans.size();i++){
  60. cout<<ans[i]<<endl;
  61. }
  62. return 0;
  63. }
Success #stdin #stdout 0s 5312KB
stdin
8
2 2 3 4 0 1 2 0
stdout
5
1