BZOJ4567[Scoi2016]背单词

时间:2023-03-08 20:10:38
BZOJ4567[Scoi2016]背单词

4567: [Scoi2016]背单词

Time Limit: 10 Sec Memory Limit: 256 MB

Submit: 304 Solved: 114

[Submit][Status][Discuss]

Description

Lweb 面对如山的英语单词,陷入了深深的沉思,“我怎么样才能快点学完,然后去玩三国杀呢?”。这时候睿智

的凤老师从远处飘来,他送给了 Lweb 一本计划册和一大缸泡椒,他的计划册是长这样的:

—————

序号 单词

—————

1

2

……

n-2

n-1

n

—————

然后凤老师告诉 Lweb ,我知道你要学习的单词总共有 n 个,现在我们从上往下完成计划表,对于一个序号为 x

的单词(序号 1...x-1 都已经被填入):

  1. 如果存在一个单词是它的后缀,并且当前没有被填入表内,那他需要吃 n×n 颗泡椒才能学会;
  2. 当它的所有后缀都被填入表内的情况下,如果在 1...x-1 的位置上的单词都不是它的后缀,那么你吃 x 颗泡

    椒就能记住它;
  3. 当它的所有后缀都被填入表内的情况下,如果 1...x-1的位置上存在是它后缀的单词,所有是它后缀的单词中

    ,序号最大为 y ,那么你只要吃 x-y 颗泡椒就能把它记住。

    Lweb 是一个吃到辣辣的东西会暴走的奇怪小朋友,所以请你帮助 Lweb ,寻找一种最优的填写单词方案,使得他

    记住这 n 个单词的情况下,吃最少的泡椒。

Input

输入一个整数 n ,表示 Lweb 要学习的单词数。接下来 n 行,每行有一个单词(由小写字母构成,且保证任意单

词两两互不相同)1≤n≤100000, 所有字符的长度总和 1≤|len|≤510000

Output

Lweb 吃的最少泡椒数

Sample Input

2

a

ba

Sample Output

2

题解

这道题我最开始做时竟然考虑了条件一。显然条件一是最不优的,我们根本不用考虑它,所以单词如果有后缀先把后缀填入表格中。

我们将单词倒着插入Tire中,之后根据Tire建树。先填父亲再填儿子这样每个单词的后缀填完了才会被填。之后根据贪心,先填Size小的儿子。因为将Size小的先填可以减少后面儿子的代价,而先填大的会增加代价。根据这个贪心我们就可以算出答案了。

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std; typedef long long LL;
LL ans;
const int Maxn = 100005, MS = 510005, Size = 26;
int Stack[Maxn], top, Son[MS][Size], totNode;
int to[MS], next[MS], head[MS], totE, totp, Siz[MS];
bool mark[MS]; void Adde(int a, int b) {
to[++totE] = b; next[totE] = head[a];
head[a] = totE;
} void Insert(char *S) {
int u = 0; char idx;
while (*S) {
idx = (*S--) - 'a';
if (!Son[u][idx]) Son[u][idx] = ++totNode;
u = Son[u][idx];
}
mark[u] = true;
} void Make_Tree(int u, int cur) {
if (mark[cur]) Adde(u, ++totp), Siz[u = totp] = 1;
for (int i = 0; i < Size; ++i)
if (Son[cur][i]) Make_Tree(u, Son[cur][i]);
} void Get_Siz(int u) {
for (int i = head[u]; i; i = next[i])
Get_Siz(to[i]), Siz[u] += Siz[to[i]];
} int id; bool cmp(const int &a, const int &b) {
return Siz[a] < Siz[b];
} void Cal(int u, int fa) {
++id; ans += id - fa; fa = id;
int l = top + 1, r = top;
for (int i = head[u]; i; i = next[i])
Stack[++r] = to[i];
sort(Stack + l, Stack + r + 1, cmp);
top = r;
for (int i = l; i <= r; ++i)
Cal(Stack[i], fa);
top = l - 1;
} char tmpS[MS]; int main() {
int n, len; scanf("%d", &n);
while (n--) {
scanf("%s", tmpS + 1); len = strlen(tmpS + 1);
Insert(tmpS + len);
}
Make_Tree(0, 0); Get_Siz(0); Cal(0, 1);
//printf("%d\n", totp);
printf("%lld\n", ans);
return 0;
}