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)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] 任何区间的最小值的下标都相等

题解:假设前面的都符合了,在判断到第i个时,判断前面第一个比a[i], b[i] 小的位置k1, k2是否相同,因为在这个范围内,是a[i]和b[i]小,k1 k2 往前就是已经符合好的了

单调栈

#include<bits/stdc++.h>
using namespace std;
const int N=1e5+5;
int a[N],b[N];
int qa[N],qb[N];
int ta,tb;
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]);
        }
        ta=0,tb=0;
        int ans=0;
        for(int i=1;i<=n;i++){
            if(a[i]>qa[ta]&&b[i]>qb[tb]){
                qa[++ta]=a[i];
                qb[++tb]=b[i];
                ans=i;
            }
            else if(a[i]<qa[ta]&&b[i]<qb[tb]){
                while(a[i]<qa[ta]) ta--;
                while(b[i]<qb[tb]) tb--;
                qa[++ta]=a[i];
                qb[++tb]=b[i];
                if(ta!=tb) break;
                else ans=i;
            }
            else break;
        }
        printf("%d\n",ans);
    }
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值