2019牛客多校第一场A-Equivalent Prefixes

原题地址

传送门

解题思路

先用单调栈求出两个序列中每一个数左边第一个小于自己的数的下标, 存入a[], b[]。然后按照1~n的顺序循环,比较 a[i]和b[i]是否相等,如果不相等则退出循环,此时最后一个相等的就是答案。
假设前1 ~ n-1已经满足了条件,此时判断1 ~ n是否可行,就是判断l~n是否都成立,如果a[n] < b[n], 那么当l=b[n]时,序列1的RBQ为b[n],序列2的为n,明显不成立,a[n] > b[n]同理。当a[n]等于b[n]时,l>a[n]的情况RBQ都为n,l<=n的时候由于第n个数已经可能是最小的,所以对前面没有影响,显然成立了。

代码如下

#include <bits/stdc++.h>
#define INF 0x3f3f3f3f
using namespace std;
typedef long long ll;

inline int read(){
    int res = 0, w = 0; char ch = 0;
    while(!isdigit(ch)){
        w |= ch == '-', ch = getchar();
    }
    while(isdigit(ch)){
        res = (res << 3) + (res << 1) + (ch ^ 48);
        ch = getchar();
    }
    return w ? -res : res;
}

const int N = 100005;

struct T{
    int val, i;
    T(int val, int i): val(val), i(i){}
};
stack<T> sta1, sta2;
int a[N], b[N];


int main()
{
    int n;
    while(scanf("%d", &n) != EOF){
        for(int i = 1; i <= n; i ++){
            int x = read();
            while(!sta1.empty() && sta1.top().val > x)
                sta1.pop();
            if(!sta1.empty())
                a[i] = sta1.top().i;
            else
                a[i] = 0;
            sta1.push(T(x, i));
        }
        for(int i = 1; i <= n; i ++){
            int x = read();
            while(!sta2.empty() && sta2.top().val > x)
                sta2.pop();
            if(!sta2.empty())
                b[i] = sta2.top().i;
            else
                b[i] = 0;
            sta2.push(T(x, i));
        }
        while(!sta1.empty())
            sta1.pop();
        while(!sta2.empty())
            sta2.pop();
        int ans = 0;
        for(int i = 1; i <= n; i ++){
            if(a[i] == b[i])
                ans = i;
            else
                break;
        }
        printf("%d\n", ans);
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/whisperlzw/p/11210261.html
今日推荐