POJ Colored Sticks(2513) -trie树&欧拉回路

来源:互联网 发布:蜜丝佛陀好用吗.知乎 编辑:程序博客网 时间:2024/06/04 22:39

题意:给你n根木棒,每个木棒两端都涂有颜色,任意两根木棒可以连在一起,如果他们有一端颜色是相同的,问你最后是否能把所有的木棒连成一根。

题解:神奇的trie &欧拉回路(用map水的TLE了难过

注:COPY的题解,第一见识trie &学习了结构体定义时初始化 &一些新的函数(new开辟类型新空间,要访问new所开辟的结构体空间,无法直接通过变量名进行,只能通过赋值的指针进行访问.

#define INF 0x7fffffff#define eps (1e-9)#define clearto(s,x) memset(s,x,sizeof(s))using namespace std;typedef long long llong;int n,m,tot=0;int du[500009],fa[500009];char a[15],b[15];struct trie{    int id;  bool end;      trie *next[26];    trie()    {   id =-1;   end =0;   for(int i=0;i<26;i++)  next[i] =NULL;   }}   *root;int getid(char *s){    trie *tmp =root;    for(int i=0;i<strlen(s);i++){        if(tmp->next[s[i]-97] ==NULL)        {  tmp->next[s[i]-97] =new trie;  }        tmp =tmp->next[s[i]-97];    }    if(tmp->end)  return tmp->id;    tmp->end =true;      tmp->id =tot;   tot++;    return  tmp->id;}int find(int x){    if(fa[x]!=x) fa[x] =find(fa[x]);     return fa[x];}void link(int x,int y) {  fa[find(x)] =  fa[find(y)];   }int main(){    //freopen("D:\data.txt","r",stdin);    int TT,i,k,t=0;    root = new trie;    clearto(du,0);    for(i=0;i<500005;i++)       fa[i] =i;    while(scanf("%s %s",a,b)!=EOF)    {        int x = getid(a), y = getid(b);        du[x]++; du[y]++;     link(x,y);    }    int old =0;    for(i=0;i<tot;i++) if(du[i]&1)  old++;    int f =find(1);    for(i=0;i<tot;i++) if(find(i)!=f) { old=-1; break; }    printf("%s",(old==0||old==2)? "Possible":"Impossible");    return 0;}


0 0
原创粉丝点击