牛客多校__Equivalent Prefixes

鏈接:https://ac.nowcoder.com/acm/contest/881/A
來源:牛客網
 

時間限制:C/C++ 2秒,其他語言4秒
空間限制:C/C++ 524288K,其他語言1048576K
64bit IO Format: %lld

題目描述

Two arrays u and v each with m distinct elements are called equivalent if and only if RMQ(u,l,r)=RMQ(v,l,r)RMQ(u,l,r)=RMQ(v,l,r) for all 1≤l≤r≤m1≤l≤r≤m
where RMQ(w,l,r)RMQ(w,l,r) denotes the index of the minimum element among wl,wl+1,…,wrwl,wl+1,…,wr.
Since the array contains distinct elements, the definition of minimum is unambiguous.

Bobo has two arrays a and b each with n distinct elements. Find the maximum number p≤np≤n where {a1,a2,…,ap}{a1,a2,…,ap} and {b1,b2,…,bp}{b1,b2,…,bp} are equivalent.

輸入描述:

The input consists of several test cases and is terminated by end-of-file.

The first line of each test case contains an integer n.
The second line contains n integers a1,a2,…,ana1,a2,…,an.
The third line contains n integers b1,b2,…,bnb1,b2,…,bn.

* 1≤n≤1051≤n≤105
* 1≤ai,bi≤n1≤ai,bi≤n
* {a1,a2,…,an}{a1,a2,…,an} are distinct.
* {b1,b2,…,bn}{b1,b2,…,bn} are distinct.
* The sum of n does not exceed 5×1055×105.

輸出描述:

For each test case, print an integer which denotes the result.

示例1

輸入

複製

2
1 2
2 1
3
2 1 3
3 1 2
5
3 1 5 2 4
5 2 4 3 1

輸出

複製

1
3
4

題意:求一個最大的p使得對於1到p的範圍內,a數組和b數組裏的任意(l,r)(l>=1&&r<=p)都可以滿足條件,即l到r之間的最小值得下標相同

題解:用單調棧預處理出每個下標下的值能影響的最左邊的位置,然後對比O(n)比較就可以了

#include <bits/stdc++.h>

using namespace std;

const int maxn = 1e5+9;
typedef long long ll;
const ll mod = 1e9+7;

int a[maxn],b[maxn];
int A[maxn],B[maxn];
int S[maxn],ind[maxn];

int main(){
    int n;
    while(~scanf("%d",&n)){
        for(int i=1;i<=n;i++)scanf("%d",&a[i]);
        for(int i=1;i<=n;i++)scanf("%d",&b[i]);

        int tot=0;

        for(int i=1;i<=n;i++){
            if(tot&&S[tot-1]>a[i]){
                while(tot&&S[tot-1]>a[i])--tot;
                A[i]=ind[tot];
                S[tot++]=a[i];
            }
            else {
                A[i]=i;
                ind[tot]=i;
                S[tot++]=a[i];
            }
        }

        tot=0;
        for(int i=1;i<=n;i++){
            if(tot&&S[tot-1]>b[i]){
                while(tot&&S[tot-1]>b[i])--tot;
                B[i]=ind[tot];
                S[tot++]=b[i];
            }
            else {
                B[i]=i;
                ind[tot]=i;
                S[tot++]=b[i];
            }
        }
//        for(int i=1;i<=n;i++){
//            cout<<A[i]<<" "<<B[i]<<endl;
//        }

        int p=0;
        for(int i=1;i<=n;i++){
            if(A[i]==B[i]){
                p=i;
            }
            else break;
        }
        printf("%d\n",p);
    }
    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章