bzoj 4567 [Scoi2016]背单词 贪心+字典树

题面

题目传送门

解法

考虑将每一个单词翻转,就变成询问前缀了

显然,我们不能让1这种情况存在,否则答案不会更优

那么,对反转后的字符串建一棵Trie,然后父节点一定在子节点之前被选择

考虑如何使最后的代价最小

显然,子树小的应该先被选择,因为这样可以使\(\sum x-y\)尽量小

那么就是一个简单的贪心了

时间复杂度:\(O(\sum|s_i|\ log\ n)\)(中间有排序)

代码

#include <bits/stdc++.h>
#define N 510010
using namespace std;
template <typename node> void chkmax(node &x, node y) {x = max(x, y);}
template <typename node> void chkmin(node &x, node y) {x = min(x, y);}
template <typename node> void read(node &x) {
	x = 0; int f = 1; char c = getchar();
	while (!isdigit(c)) {if (c == '-') f = -1; c = getchar();}
	while (isdigit(c)) x = x * 10 + c - '0', c = getchar(); x *= f;
}
struct Trie {
	int id, child[26];
} t[N];
struct Edge {
	int next, num;
} e[N];
int cnt, tot, len, f[N], siz[N], pos[N];
char st[N];
void add(int x, int y) {
	e[++cnt] = (Edge) {e[x].next, y};
	e[x].next = cnt;
}
void ins(char *st, int id) {
	int len = strlen(st), now = 0;
	for (int i = len - 1; ~i; i--) {
		int x = st[i] - 'a';
		if (!t[now].child[x]) t[now].child[x] = ++tot;
		now = t[now].child[x];
	}
	t[now].id = id;
}
void dfs(int x, int fa) {
	if (t[x].id) add(fa, t[x].id), f[t[x].id] = fa, fa = t[x].id;
	for (int i = 0; i < 26; i++)
		if (t[x].child[i]) dfs(t[x].child[i], fa);
}
void update(int x) {
	siz[x] = 1;
	for (int p = e[x].next; p; p = e[p].next) {
		int k = e[p].num; update(k);
		siz[x] += siz[k];
	}
}
void getseq(int x) {
	if (x) pos[x] = ++len;
	vector <pair <int, int> > v;
	for (int p = e[x].next; p; p = e[p].next) {
		int k = e[p].num;
		v.push_back(make_pair(siz[k], k));
	}
	sort(v.begin(), v.end());
	for (int i = 0; i < v.size(); i++)
		getseq(v[i].second);
}
int main() {
	int n; read(n); cnt = n;
	for (int i = 1; i <= n; i++)
		scanf(" %s", st), ins(st, i);
	dfs(0, 0); update(0);
	getseq(0); long long ans = 0;
	for (int i = 1; i <= n; i++) ans += pos[i] - pos[f[i]];
	cout << ans << "\n";
	return 0;
}

posted @ 2018-08-15 18:23  谜のNOIP  阅读(113)  评论(0编辑  收藏  举报