Advertisement
ekzolot

Untitled

Sep 18th, 2022
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.24 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. using namespace std;
  4. int main(){
  5.     int n;
  6.     cin>>n;
  7.     vector <int> a(n);
  8.     vector <int> b(n);
  9.     for (int i=0; i<n; i++){
  10.         cin>>a[i];
  11.     }
  12.     for (int i=0; i<n; i++){
  13.         cin>>b[i];
  14.     }
  15.     int l=20;
  16.     vector<vector<int>> tables_a(n, vector <int> (l));
  17.     for (int i=0; i<n; i++){
  18.         tables_a[i][0]=a[i];
  19.     }
  20.     for (int j=1; j<l; j++){
  21.         for (int i=0; i+(1<<j)<=n; i++){
  22.             tables_a[i][j]=max(tables_a[i][j-1], tables_a[i+(1<<j-1)][j-1]);
  23.         }
  24.     }
  25.     vector<vector<int>> tables_b(n, vector <int> (l));
  26.     for (int i=0; i<n; i++){
  27.         tables_b[i][0]=b[i];
  28.     }
  29.     for (int j=1; j<l; j++){
  30.         for (int i=0; i+(1<<j)<=n; i++){
  31.             tables_b[i][j]=min(tables_b[i][j-1], tables_b[i+(1<<j-1)][j-1]);
  32.         }
  33.     }
  34.     vector <int> powers(n+1);
  35.     for (int i=2; i<=n; i++){
  36.         powers[i]=powers[i/2]+1;
  37.     }
  38.     int ans=0;
  39.     for (int L=0; L<n; L++){
  40.         int r1=L;
  41.         int r2=n-1;
  42.         int m, k, ans_a, ans_b;
  43.         while (r1<r2-1){
  44.             m=(r1+r2)/2;
  45.             k=powers[m-L+1];
  46.             ans_a=max(tables_a[L][k], tables_a[m-(1<<k)+1][k]);
  47.             ans_b=min(tables_b[L][k], tables_b[m-(1<<k)+1][k]);
  48.             if (ans_a<=ans_b){
  49.                 r1=m;
  50.             }
  51.             else{
  52.                 r2=m;
  53.             }
  54.         }
  55.         int r3=L;
  56.         int r4=n-1;
  57.         while (r3<r4-1){
  58.             m=(r3+r4)/2;
  59.             k=powers[m-L+1];
  60.             ans_a=max(tables_a[L][k], tables_a[m-(1<<k)+1][k]);
  61.             ans_b=min(tables_b[L][k], tables_b[m-(1<<k)+1][k]);
  62.             if (ans_a<ans_b){
  63.                 r3=m;
  64.             }
  65.             else{
  66.                 r4=m;
  67.             }
  68.         }
  69.         k=powers[r3-L+1];
  70.         ans_a=max(tables_a[L][k], tables_a[r3-(1<<k)+1][k]);
  71.         ans_b=min(tables_b[L][k], tables_b[r3-(1<<k)+1][k]);
  72.         if (ans_a==ans_b){
  73.             ans++;
  74.         }
  75.         k=powers[r2-L+1];
  76.         ans_a=max(tables_a[L][k], tables_a[r2-(1<<k)+1][k]);
  77.         ans_b=min(tables_b[L][k], tables_b[r2-(1<<k)+1][k]);
  78.         if (ans_a==ans_b){
  79.             ans++;
  80.         }
  81.         ans+=r1-r3;
  82.     }
  83.     cout<<ans<<"\n";
  84. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement