zoukankan      html  css  js  c++  java
  • 洛谷P3346 [ZJOI2015]诸神眷顾的幻想乡(广义后缀自动机)

    题意

    题目链接

    Sol

    广义SAM的板子题。

    首先叶子节点不超过20,那么可以直接对每个叶子节点为根的子树插入到广义SAM中。

    因为所有合法的答案一定是某个叶子节点为根的树上的一条链,因此这样可以统计出所有合法的答案

    然后就是经典的本质不同子串问题了,(ans = sum len[i] - len[fa[i]])

    #include<bits/stdc++.h>
    #define LL long long 
    using namespace std;
    const int MAXN = 2e6 + 10;
    inline int read() {
    	char c = getchar(); int x = 0, f = 1;
    	while(c < '0' || c > '9') {if(c == '-') f = -1; c = getchar();}
    	while(c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
    	return x * f;
    }
    int N, C, a[MAXN], deg[MAXN];
    namespace SAM {
    	int fa[MAXN], len[MAXN], ch[MAXN][11], tot = 1, root = 1, las = 1;
    	int insert(int x, int pre) {
    		int now = ++tot; len[now] = len[pre] + 1;
    		for(; pre && !ch[pre][x]; pre = fa[pre]) ch[pre][x] = now;
    		if(!pre) {fa[now] = root; return now;}
    		int q = ch[pre][x];
    		if(len[q] == len[pre] + 1) fa[now] = q;
    		else {
    			int nq = ++tot; fa[nq] = fa[q]; len[nq] = len[pre] + 1;
    			memcpy(ch[nq], ch[q], sizeof(ch[q]));
    			for(; pre && ch[pre][x] == q; pre = fa[pre]) ch[pre][x] = nq;
    			fa[q] = fa[now] = nq;
    		}
    		return now;
    	}
    	LL calc() {
    		LL ans = 0;
    		for(int i = 1; i <= tot; i++) ans += len[i] - len[fa[i]];
    		return ans;
    	}
    }
    vector<int> v[MAXN], node;
    void dfs(int x, int _fa, int p) {
    	p = SAM::insert(a[x], p);
    	for(auto &to : v[x]) {
    		if(to == _fa) continue;
    		dfs(to, x, p);
    	}
    }	
    int main() {
    	N = read(); C = read();
    	for(int i = 1; i <= N; i++) a[i] = read();
    	for(int i = 1; i <= N - 1; i++) {
    		int x = read(), y = read();
    		v[x].push_back(y); deg[x]++;
    		v[y].push_back(x); deg[y]++;
    	}
    	for(int i = 1; i <= N; i++) 
    		if(deg[i] == 1) SAM::las = 1, dfs(i, 0, 1);
    	cout << SAM::calc();
    	return 0;
    }
    
  • 相关阅读:
    Python——数据类型之list、tuple
    Python——数据类型初步:Numbers
    Python——初识Python
    Python——开篇之词
    PAT——乙级1028
    PAT——甲级1009:Product of Polynomials;乙级1041:考试座位号;乙级1004:成绩排名
    PAT——甲级1065:A+B and C(64bit) 乙级1010一元多项式求导
    PAT——甲级1046S:shortest Distance
    PAT——甲级1042:Shuffling Mashine
    特征值和特征向量
  • 原文地址:https://www.cnblogs.com/zwfymqz/p/10405409.html
Copyright © 2011-2022 走看看