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


    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的RMQ为b[n],序列2的为n,明显不成立,a[n] > b[n]同理。当a[n]等于b[n]时,l>a[n]的情况RMQ都为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
    ", ans);
        }
        return 0;
    }
    
  • 相关阅读:
    ibatis 批量更新(一)
    eclipse tomcat路径更改后启动报错
    xftp Initialize Flexnet Service failed / Error code: 50003
    百度网盘 文件名中(文件)含有敏感词
    一人之下第二季百度云高清下载
    React Native Mac配置指南
    Androd自己定义控件(三)飞翔的小火箭
    关于职位规划
    SSH框架之Struts(3)——Struts的执行流程之核心方法
    HDU 4891 The Great Pan (字符串处理)
  • 原文地址:https://www.cnblogs.com/whisperlzw/p/11210261.html
Copyright © 2020-2023  润新知