luogu P3065 first——trie树相关

题目描述

Bessie has been playing with strings again. She found that by

changing the order of the alphabet she could make some strings come before all the others lexicographically (dictionary ordering).

For instance Bessie found that for the strings "omm", "moo", "mom", and "ommnom" she could make "mom" appear first using the standard alphabet and that she could make "omm" appear first using the alphabet

"abcdefghijklonmpqrstuvwxyz". However, Bessie couldn't figure out any way to make "moo" or "ommnom" appear first.

Help Bessie by computing which strings in the input could be

lexicographically first by rearranging the order of the alphabet. To compute if string X is lexicographically before string Y find the index of the first character in which they differ, j. If no such index exists then X is lexicographically before Y if X is shorter than Y. Otherwise X is lexicographically before Y if X[j] occurs earlier in the alphabet than Y[j].

给出n个字符串,问哪些串能在特定的字母顺序中字典序最小。

    -by luogu

http://daniu.luogu.org/problem/show?pid=3065



字典(trie)树,没什么好讲的;

建字典树后,如何check单词?

首先性质1:

  一个单词的前缀是单词的单词非法;

--显然,无论如何规定字典序,空就是最高的;

然后在字典树上i位置选j字母——意味着我们认为j字母比i的其他子节点小,假设k字母正是这样一个子节点;

这样的话,继续走下去时,如果在某个节点时,我们想走k字母但是发现j字母也是这个节点的儿子,那我们就走不了k了;

然后这个单词非法;

可以考虑用拓扑排序的思想规定大小;

(如果可以走j,则其它子节点字母向j连有向边构成图,然后check就是从一个节点dfs,若遍历到一个点,他也是当前父节点的一个儿子,则单词非法,先check再建边);

我一开始觉得这个方法效率玄学;

然而其实图中无环所以dfs是单次O(26)的,于是,总效率是O(num*26)的(num总字符数)

十分合适;

代码如下:

 #include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;
struct Trie{
int ch[];
int flag,size;
};
Trie trie[];
int n,tot;
string word[];
string word2[];
int ans;
int e[][];
void Init();
void bui_trie();
void check(int );
int dfs(int ,int );
int main()
{
int i,j,k;
Init();
scanf("%d",&n);
bui_trie();
for(i=;i<=n;i++){
memset(e,,sizeof(e));
check(i);
}
printf("%d\n",ans);
for(i=;i<=ans;i++)
cout<<word2[i]<<'\n';
}
void Init(){
memset(trie,,sizeof(trie));
n=tot=ans=;
}
void bui_trie(){
int i,j,k;
for(i=;i<=n;i++){
cin>>word[i];k=;
for(j=;j<word[i].size();j++){
if(!trie[k].ch[word[i][j]-'a'])
trie[k].ch[word[i][j]-'a']=++tot;
k=trie[k].ch[word[i][j]-'a'];
}
trie[k].flag=;
}
}
void check(int x){
int i,j,k=,l;
for(i=;i<word[x].size();i++){
if(trie[k].flag)return;
j=trie[k].ch[word[x][i]-'a'];
if(dfs(word[x][i]-'a',k))
return;
for(l=;l<=;l++)
if(trie[k].ch[l]&&l!=word[x][i]-'a')
e[l][++e[l][]]=word[x][i]-'a';
k=j;
}
word2[++ans]=word[x];
}
int dfs(int now,int k){
int re=,i;
for(i=;i<=e[now][];i++)
if(!trie[k].ch[e[now][i]]&&!re)
re=dfs(e[now][i],k);
else
return ;
return re;
}
上一篇:Jquery判断页面图片是否加载失败,加载失败则显示默认图片


下一篇:[Ynoi2016]这是我自己的发明(莫队)