Prefix Equality 【DP | 哈希】

E - Prefix Equality

题意:给出两段整数序列a,b,接着是q次询问,询问给出两个整数x,y,问a的前x位数字和b的前y位数字种类是否完全相同。

DP的思想!

  • 我们只关心a前x位数字储存的信息和b前y位储存的信息
  • 信息储存什么东西呢?对于这个题,数字可能相同,我们只关心数字第一次出现的位置,储存到prea里面
  • ansa表示对于a的前x个数字,b相应数字出现的坐标的最大值,如果a的前x数字中b中不存在某数,则设为inf。
#include<bits/stdc++.h>
typedef long long ll;
using namespace std;
const int inf = 0x3f3f3f3f;
int a[200010], b[200010];
int main(){
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    int n;
    cin >> n;
    std::map<int, int> prea,preb;
    for (int i = 1; i <= n; i ++ ) {
        cin >> a[i];
        if(!prea.count(a[i]))prea[a[i]] = i;
    }
    for (int i = 1; i <= n; i ++ ) {
        cin >> b[i];
        if(!preb.count(b[i]))preb[b[i]] = i;
    }
    std::vector<int> ansa(n + 1, 0), ansb(n + 1, 0);
    for (int i = 1; i <= n; i ++ ) {
        ansa[i] = max(ansa[i - 1], preb.count(a[i]) ? preb[a[i]] : inf);
        ansb[i] = max(ansb[i - 1], prea.count(b[i]) ? prea[b[i]] : inf);   
    }
 
    int t;
    cin >> t;
    while(t -- ) {
        int x, y;
        cin >> x >> y;
        cout << ((ansb[y] <= x && ansa[x] <= y) ? "Yes" : "No") << '\n';
    }   
    return 0;
}

哈希

#include<bits/stdc++.h>
typedef long long ll;
using namespace std;
const int mod = 1e9 + 7;
const int inf = 0x3f3f3f3f;
ll a[200010], b[200010];
set<ll> se;
int main(){
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    int n;
    cin >> n;
    ll s = 0;
    for (int i = 1; i <= n; i ++ ) {
        ll x;
        cin >> x;
        if(se.find(x) == se.end()) {
            s = (s + x * (x + 137) % mod * (x + 997) % mod) % mod;
        }
        a[i] = s;
        se.insert(x);
    }
    se.clear();
    s = 0;
    for (int i = 1; i <= n; i ++ ) {
        ll x;
        cin >> x;
        if(se.find(x) == se.end()) {
            s = (s + x * (x + 137) % mod * (x + 997) % mod) % mod;
        }
        b[i] = s;
        se.insert(x);
    }
    int t;
    cin >> t;
    while(t -- ) {
        int x, y;
        cin >> x >> y;
        if(a[x] == b[y]) {
            cout << "Yes\n";
        }
        else cout << "No\n";
    }   
    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值