P3966 [TJOI2013]单词

\(\color{#0066ff}{ 题目描述 }\)

小张最近在忙毕设,所以一直在读论文。一篇论文是由许多单词组成但小张发现一个单词会在论文中出现很多次,他想知道每个单词分别在论文中出现了多少次。

\(\color{#0066ff}{输入格式}\)

第一行一个整数N,表示有N个单词。接下来N行每行一个单词,每个单词都由小写字母(a-z)组成。(N≤200)

\(\color{#0066ff}{输出格式}\)

输出N个整数,第i行的数表示第i个单词在文章中出现了多少次。

\(\color{#0066ff}{输入样例}\)

3
a
aa
aaa

\(\color{#0066ff}{输出样例}\)

6
3
1

\(\color{#0066ff}{数据范围与提示}\)

30%的数据, 单词总长度不超过\(10^3\)

100%的数据,单词总长度不超过\(10^6\)

\(\color{#0066ff}{ 题解 }\)

SAM,你是真的优秀啊

把所有串以一个无关字符间隔拼起来插入SAM

然后统计鸡排统计siz

在SAM上暴力匹配

\(O(n)\)

#include<bits/stdc++.h>
using namespace std;
#define LL long long
LL in() {
	char ch; int x = 0, f = 1;
	while(!isdigit(ch = getchar()))(ch == '-') && (f = -f);
	for(x = ch ^ 48; isdigit(ch = getchar()); x = (x << 1) + (x << 3) + (ch ^ 48));
	return x * f;
}
const int maxn = 2e6 + 255;
struct SAM {
protected:
	struct node {
		node *fa, *ch[27];
		int len, siz;
		node(int len = 0, int siz = 0): fa(NULL), len(len), siz(siz) {
			memset(ch, 0, sizeof ch);
		}
	};
	node *root, *tail, *lst;
	node pool[maxn], *id[maxn];
	int c[maxn];
	void extend(int c) {
		node *o = new(tail++) node(lst->len + 1, 1), *v = lst;
		for(; v && !v->ch[c]; v = v->fa) v->ch[c] = o;
		if(!v) o->fa = root;
		else if(v->len + 1 == v->ch[c]->len) o->fa = v->ch[c];
		else {
			node *n = new(tail++) node(v->len + 1), *d = v->ch[c];
			std::copy(d->ch, d->ch + 27, n->ch);
			n->fa = d->fa, d->fa = o->fa = n;
			for(; v && v->ch[c] == d; v = v->fa) v->ch[c] = n;
		}
		lst = o;
	}
public:
	void clr() {
		tail = pool;
		root = lst = new(tail++) node();
	}
	SAM() { clr(); }
	void ins(char *s) { for(char *p = s; *p; p++) extend(*p - 'a'); }
	void getsiz() {
		int maxlen = 0;
		for(node *o = pool; o != tail; o++) c[o->len]++, maxlen = std::max(maxlen, o->len);
		for(int i = 1; i <= maxlen; i++) c[i] += c[i - 1];
		for(node *o = pool; o != tail; o++) id[--c[o->len]] = o;
		for(int i = tail - pool - 1; i; i--) {
			node *o = id[i];
			if(o->fa) o->fa->siz += o->siz;
		}
	}
	int getans(char *s) {
		node *o = root;
		for(char *p = s; *p; p++) o = o->ch[*p - 'a'];
		return o->siz;
	}
}sam;
char s[201][1000011], t[1000011];
int main() {
	int n = in();
	char *q = t;
	for(int i = 1; i <= n; i++) {
		scanf("%s", s[i]);
		for(char *p = s[i]; *p; p++) *q++ = *p;
		*q++ = 'z' + 1;
	}
	sam.ins(t);
	sam.getsiz();
	for(int i = 1; i <= n; i++) printf("%d\n", sam.getans(s[i]));
	return 0;
}
posted @ 2019-01-11 14:41  olinr  阅读(118)  评论(0编辑  收藏  举报