7k1danWhen @ 2022-05-22 10:10:34
不开O(2)RE,开了之后WA
#include<bits/stdc++.h>
using namespace std;
#define N 25001
#define M 21
int n;
int trieTop=0,trie[N*M][26]={};
bool isEnd[N*M]={},flag[N*M]={};
char key[N*M];
void Add(char s[],int len){
int u=0;
char pre;
for(int i=0;i<len;i++){
int nwC2D=s[i]-'a';
if(trie[u][nwC2D]==0) trie[u][nwC2D]=++trieTop;
key[trie[u][nwC2D]]=s[i];
pre=key[trie[u][nwC2D]];
u=trie[u][nwC2D];
}
isEnd[u]=1;
}
void Tag(char s[],int len){//for the longest
int u=0;
for(int i=0;i<len;i++){
int nwC2D=s[i]-'a';
flag[trie[u][nwC2D]]=1;
u=trie[u][nwC2D];
}
}
int printed=0,tot=0;
char ansS[N*M];
void Solve(int u){
if(isEnd[u]){
ansS[++tot]='P';
printed++;
if(printed==n){
printf("%d\n",tot);
for(int i=1;i<=tot;i++) printf("%c\n",ansS[i]);
exit(0);
}
}
int L=-1;
for(int i=0;i<26;i++){
if(trie[u][i]){
if(!flag[trie[u][i]]){
ansS[++tot]=key[trie[u][i]];
Solve(trie[u][i]);
ansS[++tot]='-';
}
else if(flag[trie[u][i]]) L=i;
}
}
if(L!=-1){
ansS[++tot]=key[trie[u][L]];
Solve(trie[u][L]);
ansS[++tot]='-';
}
}
int main(){
scanf("%d",&n);
char tmpS[M],longest[M];
int lenS,lenLong=0;
for(int i=1;i<=n;i++){
scanf("%s",tmpS);
lenS=strlen(tmpS);
Add(tmpS,lenS);
if(lenS>lenLong){
lenLong=lenS;
strcpy(longest,tmpS);
}
}
Tag(longest,lenLong);
Solve(0);
return 0;
}
/*
4
print
princ
the
poem
*/
by 7k1danWhen @ 2022-05-22 10:34:32
已会,ansS
数组需要开到N*M*2
,因为一个字符输出一次之后还要在删除一次
此贴完结