Description
给n个串,对于每个串输出是否存在一种字符的大小关系使得这个串是字典序最小的
总长<=3e5
Solution
首先如果串A是串B的前缀那么B肯定不会是最小的
要让一个串S字典序最小,也就是所有与S前缀相同的串T,S和T不同的第一个字符位i我们得钦定S[i]<T[i]
推到这个结论就很好做了,我们建trie,然后用单向边表示字母的大小关系,若出现了环说明肯定不合法
Code
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <vector>
#include <queue>
#define rep(i,st,ed) for (int i=st;i<=ed;++i)
#define fill(x,t) memset(x,t,sizeof(x))
const int N=500010;
struct edge {int y,next;} e[N];
int rec[N][26],st[N],len[N],tot;
int d[55],ls[55],edCnt;
char str[N];
bool vis[N],wjp[55][55];
void add_edge(int x,int y) {
e[++edCnt]=(edge) {y,ls[x]}; ls[x]=edCnt;
}
bool check(int id) {
fill(d,0);
fill(ls,0);
fill(wjp,0);
edCnt=0; int x=0;
rep(i,st[id],st[id]+len[id]-1) {
int tar=str[i]-'a';
if (vis[x]) return 0;
rep(j,0,25) if (rec[x][j]&&j!=tar&&!wjp[tar][j]) {
wjp[tar][j]=1;
add_edge(tar,j); d[j]++;
}
x=rec[x][tar];
}
std:: queue <int> que;
rep(i,0,25) if (!d[i]) {
que.push(i);
}
for (;!que.empty();) {
int x=que.front(); que.pop();
for (int i=ls[x];i;i=e[i].next) {
if (!(--d[e[i].y])) que.push(e[i].y);
}
}
rep(i,0,25) if (d[i]) return 0;
return 1;
}
int main(void) {
int n; scanf("%d",&n); getchar();
rep(i,1,n) {
st[i]=st[i-1]+len[i-1]; int x=0;
for (char ch=getchar();ch!='\n';ch=getchar()) {
str[st[i]+len[i]]=ch; len[i]++;
if (!rec[x][ch-'a']) rec[x][ch-'a']=++tot;
x=rec[x][ch-'a'];
}
vis[x]=1;
}
std:: vector <int> prt;
rep(i,1,n) if (check(i)) prt.push_back(i);
printf("%d\n", prt.size());
for (int i=0;i<prt.size();++i) {
rep(j,st[prt[i]],st[prt[i]]+len[prt[i]]-1) {
putchar(str[j]);
} putchar('\n');
}
return 0;
}