Advertisement
a53

chain

a53
Nov 27th, 2019
181
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.62 KB | None | 0 0
  1. #include<iostream>
  2. #include<iomanip>
  3. #include<stack>
  4. using namespace std;
  5.  
  6. const int N=1000002;
  7. int n;
  8. int a[N];
  9. int p[N];
  10. int d[N];
  11.  
  12. int main()
  13. {
  14. cin >> n;
  15. for(int i=0;i<n;i++) cin >> a[i];
  16.  
  17. // O(n)
  18. stack<int> s;
  19. for(int i=1;i<n;i++)
  20. {
  21. s.push(i-1);
  22. while(!s.empty())
  23. {
  24. int j=s.top();
  25. if(a[j]>=a[i]) break;
  26. if(a[j]<a[i]) {p[j]=i; s.pop();}
  27. }
  28. }
  29.  
  30. // chains
  31.  
  32. d[n-1]=0;
  33. for(int i=n-2;i>=0;i--)
  34. {
  35. if(p[i]==0) d[i]=0;
  36. else d[i]=1+d[p[i]];
  37. }
  38.  
  39. cout << d[0];
  40. for(int i=1; i<n; i++) cout << " " << d[i];
  41. cout << endl;
  42.  
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement