您的位置:首页 > 产品设计 > UI/UE

UOJ 13 [UER #1]跳蚤OS

2016-08-30 17:48 183 查看
trie树。

在trie上建每一条路径的字符串。节点加一个go指针,如果go不为NULL则说明他是快捷方式,并且go指向它指向的文件夹。然后找一找,连一连,就好了。

其实我觉得如果对于每个文件夹,把名字哈希之后视为一个节点,依然可做。但是太懒不想打哈希。

#include<cstdio>
#include<cstring>
using namespace std;
char s[500005], t[500005];
struct node
{
node *next[30], *go, *fa;
int v;
node(){fa=go=NULL;memset(next,NULL,sizeof(next));}
};
int pack(char c)
{
if(c=='/')return 26;
else return c-'a';
}
char unpack(int c)
{
if(c==26)return '/';
else return c+'a';
}
struct TRIE
{
node *root;
void init()
{
root= new node;
}
node* inser(char *s)
{
node *p=root;
for(int i = 0; s[i]; i++)
{
int c=pack(s[i]);
if(!p->next[c])
{
p->next[c]=new node;
p->next[c]->fa=p;
p->next[c]->v=c;
}
p=p->next[c];
if(c==26 && p->go)
p=p->go;
}
if(p->v!=26)
{
if(!p->next[26])
{
p->next[26]=new node;
p->next[26]->fa=p;
p->next[26]->v=26;
}
p=p->next[26];
if(p->go)p=p->go;
}
return p;
}
}trie;
int main()
{
int n, m;
scanf("%d%d",&n,&m);
trie.init();
for(int i = 1; i <= n; i++)
{
scanf("%s%s",s,t);
node *p=trie.inser(s);
node *q=trie.inser(t);
p->go=q;
}
for(int i = 1; i <= m; i++)
{
scanf("%s",s);
node *p=trie.inser(s);
if(p->fa!=trie.root)p=p->fa;
int j=0;
while(p!=trie.root)
{
t[j++]=unpack(p->v);
p=p->fa;
}
for(int k = j-1; k >= 0; k--)
printf("%c",t[k]);
puts("");
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: