poj2513- Colored Sticks 字典树+欧拉通路判断

题目链接:http://poj.org/problem?id=2513

思路很容易想到就是判断欧拉通路

预处理时用字典树将每个单词和数字对应即可

刚开始在并查集处理的时候出错了

代码:

  1 #include<iostream>
  2 #include<cstdlib>
  3 #include<cstdio>
  4 #include<cstring>
  5 using namespace std;
  6 int color;
  7 #define maxn 26
  8 #define MAX 500010
  9 int parent[MAX];
 10 int degree[MAX];
 11 class Trie
 12 {
 13  public:
 14    bool flag;
 15    int id;
 16    Trie *next[maxn];
 17 };
 18 Trie  *root=new Trie;
 19 void init()
 20 {
 21     memset(degree,0,sizeof(degree));//存放各个点的度数
 22     memset(parent,-1,sizeof(parent));
 23     Trie *q=root;//字典树初始化
 24     for(int i=0;i<maxn;i++)
 25      q->next[i]=NULL;
 26      q->flag=false;
 27      q->id=0;
 28 }
 29 /* 并查集构建并判断是否为连通图*/
 30 int find(int x)
 31 {
 32    if(parent[x]==-1) return x;
 33    return parent[x]= find(parent[x]);
 34 
 35 }
 36 
 37 void Union(int u,int v)
 38 {
 39    int r1=find(u);
 40    int r2=find(v);
 41 
 42    if(r1!=r2)
 43       parent[r1]=r2;
 44 }
 45 int insert(char *s)
 46 {
 47    Trie *p =root;
 48 
 49    for(int i=0; s[i]!='\0' ;i++)
 50    {
 51        int d=s[i]-'a';
 52 
 53        if(p->next[d]==NULL)
 54        {
 55           Trie *temp=new Trie;
 56           for(int j=0;j<maxn;j++)
 57             temp->next[j]=NULL;
 58             temp->flag=0;
 59             temp->id=0;
 60             p->next[d]=temp;
 61        }
 62        p=p->next[d];
 63 
 64   }
 65   if(p->flag)
 66     {
 67       return p->id;
 68     }
 69   else
 70    {
 71       p->flag=1;
 72       p->id=color++;
 73       return p->id;
 74    }
 75 
 76 }
 77 void del_trie(Trie * p)
 78 {
 79    for(int i=0;i<maxn;i++)
 80       if(p->next[i])
 81          del_trie(p->next[i]);
 82 
 83    free(p);
 84 }
 85 int main()
 86 {
 87    char s1[20],s2[20];
 88    init();
 89    color=0;
 90    while(scanf("%s%s",s1,s2)!=EOF)
 91    {
 92        int num1=insert(s1);
 93        int num2=insert(s2);
 94 
 95        degree[num1]++;
 96        degree[num2]++;
 97        Union(num1,num2);
 98 
 99    }
100    int cnt1=0,cnt2=0;
101    for(int i=0;i<color;i++)//判断是佛否含欧拉通路
102    {
103       if(parent[i]==-1) cnt1++;
104       if(degree[i]%2==1) cnt2++;
105       if(cnt1>1) break;
106       if(cnt2>2) break;
107    } 
108 
109    if((cnt1==0 || cnt1==1) &&(cnt2==0 || cnt2==2))
110    printf("Possible\n");
111    else printf("Impossible\n");
112  //  del_trie(root);
113    return 0;
114    
115 }

 

posted on 2013-11-19 17:53  GyyZyp  阅读(217)  评论(0编辑  收藏  举报

导航