POJ2513-Colored Sticks

简介:
+ View Code?123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354/*<br>思路:类似图论中“一笔画”问题,两根木棒的相连接的端点是一样的颜色,(a,b)--(b,c)--(c, d)....<br>方法:trie树+并查集, 利用trie树建立字符串和某一个节点的映射,并将这些和字符串构成映射的节点建成图, 用并查集判断图的连通<br>*/<br> 1 #include<iostream>  2 #include<cstdio> 3 #include<cstring> 4 #define N 2500005*2 5 using namespace std; 6 int f[N]; 7 int indgr[N]; 8 int trie[N][26]; 9 int nodeNum, pre, cnt, oddDgr, root;10 int getFather(int x)//并查集寻找父亲节点,压缩路径11 {12      return x == f[x] ? x : f[x]=getFather(f[x]);13 }14 15 void Union(int a, int b)//并查集的合并16 {17     int fa=getFather(a), fb=getFather(b);18     if(fa!=fb) 19        f[fa]=fb;20 }21 22 int main()23 {24    char color[15];25    int i;26    for(i=0; i<N; ++i)27    f[i]=i;28    while(scanf("%s", color)!=EOF)29   {30      cnt++;31      int cur=0, L=strlen(color);32      for(i=0; i<L; ++i)33      {34         int k=color[i]-'a';35       if(!trie[cur][k])36            trie[cur][k]=++nodeNum;37       cur=trie[cur][k];38      }39    ++indgr[cur];40      if(cnt%2) pre=cur;41      else42     Union(pre, cur);43  }44   for(i=0; i<=nodeNum; ++i)45   {46     if(indgr[i]&1) ++oddDgr;47     if(indgr[i] && f[i]==i) ++root;48     if(oddDgr>2 || root>1) break;49   } 50   if((oddDgr==0 || oddDgr==2) && root==1 || oddDgr==0 && root==0)//注意空树的情况下是输出Impossible, 开始就是错在了这里51   printf("Possible\n");52   else printf("Impossible\n");53   return 0;54 }









本文转自 小眼儿 博客园博客,原文链接:http://www.cnblogs.com/hujunzheng/p/3775673.html,如需转载请自行联系原作者
目录
相关文章
|
8月前
|
算法
POJ3061 Subsequence
POJ3061 Subsequence
|
测试技术
HDU-1026,Ignatius and the Princess I(BFS+打印路径)
HDU-1026,Ignatius and the Princess I(BFS+打印路径)
POJ 1306 Combinations
POJ 1306 Combinations
95 0
|
算法 移动开发
[LeetCode]--70. Climbing Stairs
You are climbing a stair case. It takes n steps to reach to the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? 这是一个很经典的爬楼梯问题,面试也会经常遇
1129 0
|
算法
poj-3660-cows contest(不懂待定)
Description N (1 ≤ N ≤ 100) cows, conveniently numbered 1..N, are participating in a programming contest.
948 0