Guest User

frequent-7917

a guest
Mar 23rd, 2018
263
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.13 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. typedef long long ll;
  6. typedef double dbl;
  7. #define fr(x,a,b) for(ll x=a;x<b;x++)
  8. #define PB push_back
  9. #define MP make_pair
  10. #define mod 1000000007
  11. #define gmax LLONG_MAX
  12. #define gmin LLONG_MIN
  13. #define INF 2e9
  14. #define N 100005
  15. #define MAX(a,b,c) max(max(a,b),c)
  16. #define MIN(a,b,c) min(min(a,b),c)
  17.  
  18. ll a[N];
  19.  
  20. struct Tree{
  21.   ll mf; // max frequency
  22.   ll mpf; // max prefix frequency
  23.   ll msf; // max suffix frequency
  24.   ll mpn; // max prefix number
  25.   ll msn; // max suffix number
  26. };
  27.  
  28. Tree tree[4*N];
  29.  
  30. Tree merge(Tree t1,Tree t2){
  31.   Tree t;
  32.  
  33.   if(t1.msn==t2.mpn){
  34.     t.mf=MAX(t1.mf,t2.mf,t1.msf+t2.mpf);
  35.  
  36.     if(t1.mpn==t1.msn) t.mpf=t1.msf+t2.mpf;
  37.     else t.mpf=t1.mpf;
  38.  
  39.     if(t2.mpn==t2.msn) t.msf=t1.msf+t2.mpf;
  40.     else t.msf=t2.msf;
  41.   }
  42.   else{
  43.     t.mf=max(t1.mf,t2.mf);
  44.     t.mpf=t1.mpf;
  45.     t.msf=t2.msf;
  46.   }
  47.  
  48.   t.mpn=t1.mpn;
  49.   t.msn=t2.msn;
  50.  
  51.   return t;
  52. }
  53.  
  54. void build(ll node,ll start,ll end){
  55.   if(start==end){ // leaf node
  56.     tree[node].mpn=tree[node].msn=a[start];
  57.     tree[node].mf=tree[node].mpf=tree[node].msf=1;
  58.   }
  59.   else{
  60.     ll mid=(start+end)/2;
  61.     build(node*2,start,mid); // recursion on left child
  62.     build(node*2+1,mid+1,end); // recursion on right child
  63.     tree[node]=merge(tree[node*2],tree[node*2+1]); // internal(parent) node values are calculated
  64.   }
  65. }
  66.  
  67. Tree query(ll node,ll start,ll end,ll left,ll right){
  68.   if(right<start || end<left){ // node range is completely outside the query range
  69.     Tree t;
  70.     t.mf=t.mpf=t.msf=t.mpf=t.msf=0;
  71.     return t;
  72.   }
  73.   if(left<=start && end<=right){ // node range is completely inside query range
  74.     return tree[node];
  75.   }
  76.   ll mid=(start+end)/2;
  77.   Tree t1=query(node*2,start,mid,left,right);
  78.   Tree t2=query(node*2+1,mid+1,end,left,right);
  79.   return merge(t1,t2);
  80. }
  81.  
  82. int main(){
  83.   ios::sync_with_stdio(false);
  84.   cin.tie(NULL);
  85.   cout.tie(NULL);
  86.  
  87.   ll n,m,l,r;
  88.   while(cin>>n && n){
  89.     cin>>m;
  90.  
  91.     fr(i,0,n) cin>>a[i];
  92.  
  93.     build(1,0,n-1);
  94.  
  95.     fr(i,0,m){
  96.       cin>>l>>r;
  97.       l--;
  98.       r--;
  99.       cout<<query(1,0,n-1,l,r).mf<<"\n";
  100.     }
  101.   }
  102.  
  103.   return 0;
  104. }
Add Comment
Please, Sign In to add comment