2019牛客多校第一场补题 A Equivalent Prefixes (单调栈)

A Equivalent Prefixes (单调栈)
链接:https://ac.nowcoder.com/acm/contest/881/A
来源:牛客网
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)\mathrm{RMQ}(u, l, r) = \mathrm{RMQ}(v, l, r)RMQ(u,l,r)=RMQ(v,l,r) for all 1≤l≤r≤m1 \leq l \leq r \leq m1≤l≤r≤m
where RMQ(w,l,r)\mathrm{RMQ}(w, l, r)RMQ(w,l,r) denotes the index of the minimum element among wl,wl+1,…,wrw_l, w_{l + 1}, \dots, w_{r}wl​,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 \leq np≤n where {a1,a2,…,ap}{a_1, a_2, \dots, a_p}{a1​,a2​,…,ap​} and {b1,b2,…,bp}{b_1, b_2, \dots, b_p}{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,…,ana_1, a_2, \dots, a_na1​,a2​,…,an​.
The third line contains n integers b1,b2,…,bnb_1, b_2, \dots, b_nb1​,b2​,…,bn​.

  • 1≤n≤1051 \leq n \leq 10^51≤n≤105
  • 1≤ai,bi≤n1 \leq a_i, b_i \leq n1≤ai​,bi​≤n
  • {a1,a2,…,an}{a_1, a_2, \dots, a_n}{a1​,a2​,…,an​} are distinct.
  • {b1,b2,…,bn}{b_1, b_2, \dots, b_n}{b1​,b2​,…,bn​} are distinct.
  • The sum of n does not exceed 5×1055 \times 10^55×105.
    输出描述:
    For each test case, print an integer which denotes the result

输入
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
当时没想到要用单调栈维护,赛后看了题解,理解了一种思路;
题意理解为有a,b两个序列,让你找出最大的p,使得i在1-p内,a[i],b[i]的最小值的下标位置相等;
可以两个用递减的单调栈维护两个序列,可以看出,只要两个序列每个元素的左侧第一个比它小的元素位置相同,两个序列就满足RMQ,或者是单调栈内的元素相同,同样满足RMQ;
ac代码:

#include<bits/stdc++.h>
#include<map>
#define ll long long
using namespace std;
const int maxn=1e5+7;
const int INF=1e9;
ll a[maxn],b[maxn];
stack<ll >s1,s2;
int main()
{
    ll n;
    while(~scanf("%lld",&n))
    {
        while(!s1.empty())
            s1.pop();
        while(!s2.empty())
            s2.pop();
        for(int i=1;i<=n;i++)
            scanf("%lld",&a[i]);
        for(int i=1;i<=n;i++)
            scanf("%lld",&b[i]);
        s1.push(a[1]);
        s2.push(b[1]);
        int i;
        for(i=2;i<=n;i++)
        {
            while(!s1.empty()&&a[i]<s1.top())   ///奇偶分别跑一次
                s1.pop();
            s1.push(a[i]);
            while(!s2.empty()&&b[i]<s2.top())
                s2.pop();
            s2.push(b[i]);
            if(s1.size()!=s2.size())
                break;
        }
        printf("%d\n",i-1);
    }
    return 0;
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值