BZOJ3207:花神的嘲讽计划Ⅰ hash+主席树

Description
给出一个长度为n的序列,有m个询问,每次询问l~r是否存在长度为k的一个字串。


Sample Input
8 5 3
1 2 3 4 5 6 7 8
2 5 2 3 4
1 8 3 2 1
5 7 4 5 6
2 5 1 2 3
1 7 3 4 5


Sample Output
No
Yes
Yes
Yes
No


这一题用hash来求子串匹配,用一个主席树维护它。
好像挺裸的吧。。。
大概学了一下hash,发现hash好像挺好用,但是hash的匹配不一定100%正确。


#include <cstdio>
#include <cstring>

using namespace std;
typedef unsigned long long ULL;
int read() {
    int x = 0, f = 1;char ch = getchar();
    while(ch < '0' || ch > '9') {if(ch == '-') f = -1; ch = getchar();}
    while(ch >= '0' && ch <= '9') {x = x * 10 + ch - '0'; ch = getchar();}
    return x * f;
}
const int hs = 233;
const ULL inf = 18446744073709551615UL;

struct node {
    int lc, rc, c;
} t[8100000]; int cnt, rt[210000];
ULL a[210000];

void Link(int &u, ULL l, ULL r, ULL p) {
    if(!u) u = ++cnt;
    t[u].c++;
    if(l == r) return ;
    ULL mid = l / 2 + r / 2;
    if(p <= mid) Link(t[u].lc, l, mid, p);
    else Link(t[u].rc, mid + 1, r, p);
}

void Merge(int &u1, int u2) {
    if(!u1 || !u2) {u1 = u1 + u2; return ;}
    t[u1].c += t[u2].c;
    Merge(t[u1].lc, t[u2].lc);
    Merge(t[u1].rc, t[u2].rc);
}

int query(int u1, int u2, ULL l, ULL r, ULL k) {
    if(l == r) return t[u1].c - t[u2].c;
    ULL mid = l / 2 + r / 2;
    if(k <= mid) return query(t[u1].lc, t[u2].lc, l, mid, k);
    else return query(t[u1].rc, t[u2].rc, mid + 1, r, k);
}

int main() {
    int n = read(), m = read(), k = read();
    for(int i = 1; i <= n; i++) {
        int x = read();
        a[i] = a[i - 1] * hs + x;
    }
    ULL ka = 1; for(int i = 1; i <= k; i++) ka *= hs;
    for(int i = k; i <= n; i++) {
        Link(rt[i], 0, inf, a[i] - a[i - k] * ka);
        Merge(rt[i], rt[i - 1]);
    }
    for(int i = 1; i <= m; i++) {
        int x = read(), y = read();
        ULL cc = 0;
        for(int j = 1; j <= k; j++) cc = cc * hs + read();
        if(y - x + 1 < k) {
            printf("Yes\n");
            continue;
        }
        if(query(rt[y], rt[x + k - 2], 0, inf, cc)) printf("No\n");
        else printf("Yes\n");
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值