问个问题
查看原帖
问个问题
139012
wrpwrp楼主2020/7/29 17:08

请问为什么P3349不能枚举根节点直接把这棵树上每一条到叶节点的链暴力插入SAM? 这是我的不知道为啥错了的代码

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>

using namespace std;
#define R register
#define LL long long
const int N = 2e6 + 10;

inline int read() {
	char a = getchar(); int x = 0, f = 1;
	for(; a > '9' || a < '0'; a = getchar()) if(a == '-') f = -1;
	for(; a >= '0' && a <= '9'; a = getchar()) x = x * 10 + a - '0';
	return x * f;
}

struct SAM {
	int node = 1, las = 1;
	int fa[N], ch[N][20], len[N];
	inline void ins(int c) {
		int p = ++ node, now = las; las = p;
		len[p] = len[now] + 1;
		while(now && ! ch[now][c]) ch[now][c] = p, now = fa[now];
		if(! now) { fa[p] = 1; return ;}
		int x = ch[now][c];
		if(len[now] + 1 == len[x]) { fa[p] = x; return; }
		int y = ++ node; fa[y] = fa[x]; fa[x] = fa[p] = y; len[y] = len[now] + 1;
		memcpy(ch[y], ch[x], sizeof(ch[y])); 
		while(now && ch[now][c] == x) ch[now][c] = p, now = fa[now];
	}
}T;

int n, val[N];
int cnt, head[N];
struct edge { int to, next; } e[N << 1];
inline void add(int x, int y) { e[++ cnt] = {y, head[x]}; head[x] = cnt; }
int du[N];
int st[N], top;
int rt ;
inline void dfs1(int x, int fx) {
	st[++ top] = val[x];
	for(R int i = head[x]; i; i = e[i].next) {
		int y = e[i].to; 
		if(y == fx) continue; dfs1(y, x);
	}
	if(du[x] == 1 && x != rt) {
		T.las = 1;
		//for(R int i = 1; i <= top; i ++) cout << st[i] << ' '; putchar('\n');
		for(R int i = 1; i <= top; i ++) T.ins(st[i]);
	}
	top --;
}
inline void build(int x) {
	//cout << "Case : " << x << endl;
	rt = x; dfs1(x, 0);
}
int main() {
	freopen("1.in", "r", stdin);
//	freopen("a.out", "w", stdout);
	n = read(); int ppp = read();
	for(R int i = 1; i <= n; i ++) val[i] = read();
	for(R int i = 1; i < n; i ++) {
		int x = read(), y = read(); add(x, y); add(y, x);
		du[x] ++; du[y] ++; //cout << x << ' ' << y << endl;
	}
	for(R int i = 1; i <= n; i ++) 
		if(du[i] == 1) build(i);
	LL ans = 0;
	for(R int i = 1; i <= T.node; i ++) ans += (T.len[i] - T.len[T.fa[i]]);
	cout << ans << endl; 
	return 0;
}
2020/7/29 17:08
加载中...