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 个单词的情况下,吃最少的泡椒。
1≤n≤100000, 所有字符的长度总和 1≤|len|≤510000
Solution
看了几轮才看懂题意。。
大概就是要对n个串排序,使得按照统计方法代价最小。
显然第一种情况不会发生。考虑把所有串反向插入trie中,问题转变为给每个串的终点节点编号使得∑id[x]−id[fa[x]]∑id[x]−id[fa[x]]最小
这里有一个不那么显然的贪心做法。我们只抠出所有串的终点节点连成一棵树,每次走size最小的子树编号即可
Code
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <vector>
#define rep(i,st,ed) for (int i=st;i<=ed;++i)
#define drp(i,st,ed) for (int i=st;i>=ed;--i)
#define fill(x,t) memset(x,t,sizeof(x))
typedef long long LL;
const int N=1050005;
struct edge {int y,next;} e[N];
int rec[N][26],size[N],dfn[N],tot=1;
int ls[N],edCnt;
LL ans;
bool vis[N];
char str[N];
void add_edge(int x,int y) {
e[++edCnt]=(edge) {y,ls[x]}; ls[x]=edCnt;
}
void ins(char *str) {
int len=strlen(str+1);
int now=1;
drp(i,len,1) {
if (!rec[now][str[i]-'a']) rec[now][str[i]-'a']=++tot;
now=rec[now][str[i]-'a'];
}
vis[now]=1;
}
void build(int now,int fa) {
if (vis[now]) {
add_edge(fa,now);
fa=now;
}
rep(i,0,25) if (rec[now][i]) {
build(rec[now][i],fa);
}
}
void dfs(int now) {
size[now]=1;
for (int i=ls[now];i;i=e[i].next) {
dfs(e[i].y); size[now]+=size[e[i].y];
}
}
bool cmp(int x,int y) {
return size[x]<size[y];
}
void solve(int now) {
dfn[now]=++dfn[0];
std:: vector <int> vec; vec.clear();
for (int i=ls[now];i;i=e[i].next) {
vec.push_back(e[i].y);
}
if (vec.empty()) return ;
std:: sort(vec.begin(), vec.end(), cmp);
for (int i=0;i<vec.size();i++) {
solve(vec[i]); ans+=dfn[vec[i]]-dfn[now];
}
}
int main(void) {
int n; scanf("%d",&n);
rep(i,1,n) {
scanf("%s",str+1);
ins(str);
}
build(1,1);
dfs(1);
solve(1);
printf("%lld\n", ans);
return 0;
}

本文探讨了一个有趣的问题,即如何通过优化单词学习顺序,减少学习过程中的额外负担。具体而言,通过对一系列单词进行排序,使学习者在遇到具有相似后缀的单词时能够减少重复努力,从而实现高效学习。
638

被折叠的 条评论
为什么被折叠?



