zoukankan      html  css  js  c++  java
  • Codeforces 235C

    Codeforces 235C


    题目:给定一主串(S)(n)次询问,每次询问串(t)的所有循环移位串的出现的次数和

    做法:建(SAM),对于询问串(t),将他复制一份放在后边,在后缀自动机上匹配,如果匹配长度大于(|t|),就沿着(fa), 找到第一次大于(|t|)的位置,用这个状态的(right)数组更新答案。注意到可能会匹配到重复的状态,所以要对会更新答案的状态去重。

    #include <bits/stdc++.h>
    typedef long long ll;
    const int N = 1000010 << 1;
    using namespace std;
    
    struct SAM{
        int n, step[N], fa[N], ch[N][26], right[N], num[N], last, root, cnt;
    	char s[N>>1];
    	SAM(){last = root = ++cnt; }
    	void add(int x){
    		int tmp = s[x] - 'a', p = last, np = ++cnt;
    		step[last = np] = x, right[np] = 1;
    		while(p && !ch[p][tmp]) ch[p][tmp] = np, p = fa[p];
    		if(!p) fa[np] = root;
    		else{
    			int q = ch[p][tmp];
    			if(step[q] == step[p] + 1) fa[np] = q;
    			else{
    				int nq = ++cnt; step[nq] = step[p] + 1;
    				memcpy(ch[nq], ch[q], sizeof(ch[q]));
    				fa[nq] = fa[q], fa[q] = fa[np] = nq;
    				while(ch[p][tmp] == q) ch[p][tmp] = nq, p = fa[p];
    			}
    		}
    	}
        int tmp[N];
    	void calright(){
    		memset(tmp, 0, sizeof(tmp));
    		for(int i = 1; i <= cnt; i++) tmp[step[i]]++;
    		for(int i = 1; i <= n; i++) tmp[i] += tmp[i - 1];
    		for(int i = cnt; i; i--) num[tmp[step[i]]--] = i;
    		for(int i = cnt; i; i--) right[fa[num[i]]] += right[num[i]];
    	}
    	void run(){
    		scanf(" %s",s+1), n = strlen(s + 1);
    		for(int i = 1; i <= n; i++) add(i);
    		calright();
    	}
    
        char str[N];
        int len;
        set<int> S;
        ll solve() {
            scanf(" %s",str+1), len = strlen(str+1);
            for(int i = 1; i <= len; ++i) str[i+len] = str[i];
            int now = root, tmp = 0; ll ans = 0;
            for(int i = 1; i <= len+len; ++i) {
                int x = str[i]-'a';
                if(ch[now][x]) now = ch[now][x], ++tmp;
                else {
                    while(now && !ch[now][x]) now = fa[now];
                    if(!now) now = root, tmp = 0;
                    else tmp = step[now]+1, now = ch[now][x];
                }
                while(now!=1 && step[fa[now]] >= len) now = fa[now], tmp = step[now];
                if(tmp >= len) S.insert(now);
            }
            for(set<int>::iterator it = S.begin(); it != S.end(); ++it) ans += right[*it];
            S.clear();
            return ans;
        }
    } Fe;
    
    int main() {
        Fe.run();
        int q;
        scanf("%d",&q);
        while(q--) {
            printf("%I64d
    ",Fe.solve());
        }
    }
    
  • 相关阅读:
    计算一个未排序数组中排序后相邻元素的最大差值
    13 类对象的声明中加小括号{}和不加小括号{}的区别
    12 表中删除重复项
    11 常量区的内容不能被修改
    10 无向图的边
    顺时针旋转矩阵
    字符串的旋转
    动态规划算法
    贪心算法应用-最小生成树
    贪心算法应用-单元最短路径
  • 原文地址:https://www.cnblogs.com/RRRR-wys/p/10299830.html
Copyright © 2011-2022 走看看