wa了十万次终于ac了...
题目感觉描述很鬼畜,一开始理解错了...
这里搬运一下别人的“翻译”:
给你n个字符串,不同的排列有不同的代价,代价按照如下方式计算(字符串s的位置为x):
1.排在s后面的字符串有s的后缀,则代价为n^2;
2.排在s前面的字符串有s的后缀,且没有排在s后面的s的后缀,则代价为x-y(y为最后一个与s不相等的后缀的位置);
3.s没有后缀,则代价为x。
求最小代价和。
也就是自己规定字符串出现顺序达到最小代价。。。
因为是后缀,考虑将字符串反转建立trie,容易发现无论如何 1 都是代价最大的,
那么就一定有在trie上的节点一定编号大于其祖先.
简单观察发现,对于某一刻,无论选哪个节点,总代价都会增大目前能扫到的第一个标记点的总量。
也就是说除了标记点以外的其他点已经没有用了...
要使总代价最少,那么这次选的点一定要使以后增加的点最小.
所以记录一下每个点能看到的,以及这一个子树下分支总量,那么分只越少的一定是越先处理。
搞定
c++代码如下:
#include<bits/stdc++.h>
#define rep(i,x,y) for(register int i = x; i <= y; ++ i)
#define repd(i,x,y) for(register int i = x; i >= y; -- i)
using namespace std;
typedef long long ll;
template<typename T>inline void read(T&x)
{
x = 0;char c;int sign = 1;
do { c = getchar(); if(c == '-') sign = -1; }while(!isdigit(c));
do { x = x * 10 + c - '0'; c = getchar(); }while(isdigit(c));
x *= sign;
}
int trie[510100][27],size[510100],Size[500100],cnt,sz,n;ll ans;
char s[501100];bool val[510100];
vector<int>e[500100];
struct Str
{
int p,w;
bool operator < (const Str b) const { return w > b.w; }
};
inline void insert()
{
int len = strlen(s),x = 0,lst = 0;
repd(i,len - 1,0)
{
if(!trie[x][s[i] - 'a']) trie[x][s[i] - 'a'] = ++sz;
x = trie[x][s[i] - 'a'];
}
val[x] = 1;
}
void dfs(int x,int lst)
{
if(val[x]) size[lst]++,e[lst].push_back(x),lst = x;
rep(i,0,'z' - 'a')
if(trie[x][i])
dfs(trie[x][i],lst);
Size[x] = size[x];
rep(i,0,((int)e[x].size()) - 1)
Size[x] += Size[e[x][i]];
}
inline void bfs()
{
priority_queue<Str>q;
q.push((Str){0,0});cnt = 1;
while(!q.empty())
{
Str x = q.top();q.pop();
cnt = cnt - 1 + size[x.p]; ans += cnt;
rep(i,0,((int)e[x.p].size()) - 1)
q.push((Str){e[x.p][i],Size[e[x.p][i]] });
}
}
int main()
{
read(n);
rep(i,1,n)
{
scanf("%s",s);
insert();
}
dfs(0,0);
bfs();
cout << ans << endl;
return 0;
}

1917

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



