Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- using namespace std;
- int main(){
- int n;
- cin>>n;
- vector <int> a(n);
- vector <int> b(n);
- for (int i=0; i<n; i++){
- cin>>a[i];
- }
- for (int i=0; i<n; i++){
- cin>>b[i];
- }
- int l=20;
- vector<vector<int>> tables_a(n, vector <int> (l));
- for (int i=0; i<n; i++){
- tables_a[i][0]=a[i];
- }
- for (int j=1; j<l; j++){
- for (int i=0; i+(1<<j)<=n; i++){
- tables_a[i][j]=max(tables_a[i][j-1], tables_a[i+(1<<j-1)][j-1]);
- }
- }
- vector<vector<int>> tables_b(n, vector <int> (l));
- for (int i=0; i<n; i++){
- tables_b[i][0]=b[i];
- }
- for (int j=1; j<l; j++){
- for (int i=0; i+(1<<j)<=n; i++){
- tables_b[i][j]=min(tables_b[i][j-1], tables_b[i+(1<<j-1)][j-1]);
- }
- }
- vector <int> powers(n+1);
- for (int i=2; i<=n; i++){
- powers[i]=powers[i/2]+1;
- }
- int ans=0;
- for (int L=0; L<n; L++){
- int r1=L;
- int r2=n-1;
- int m, k, ans_a, ans_b;
- while (r1<r2-1){
- m=(r1+r2)/2;
- k=powers[m-L+1];
- ans_a=max(tables_a[L][k], tables_a[m-(1<<k)+1][k]);
- ans_b=min(tables_b[L][k], tables_b[m-(1<<k)+1][k]);
- if (ans_a<=ans_b){
- r1=m;
- }
- else{
- r2=m;
- }
- }
- int r3=L;
- int r4=n-1;
- while (r3<r4-1){
- m=(r3+r4)/2;
- k=powers[m-L+1];
- ans_a=max(tables_a[L][k], tables_a[m-(1<<k)+1][k]);
- ans_b=min(tables_b[L][k], tables_b[m-(1<<k)+1][k]);
- if (ans_a<ans_b){
- r3=m;
- }
- else{
- r4=m;
- }
- }
- k=powers[r3-L+1];
- ans_a=max(tables_a[L][k], tables_a[r3-(1<<k)+1][k]);
- ans_b=min(tables_b[L][k], tables_b[r3-(1<<k)+1][k]);
- if (ans_a==ans_b){
- ans++;
- }
- k=powers[r2-L+1];
- ans_a=max(tables_a[L][k], tables_a[r2-(1<<k)+1][k]);
- ans_b=min(tables_b[L][k], tables_b[r2-(1<<k)+1][k]);
- if (ans_a==ans_b){
- ans++;
- }
- ans+=r1-r3;
- }
- cout<<ans<<"\n";
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement