POJ2513 Colored Sticks 欧拉回路

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

  建立无向图,看图是否存在欧拉道路。首先判断图是否连通,可以用并查集或者一遍BFS判断,最后判断入度数就可以了。

  1 //STATUS:C++_AC_1266MS_79348KB
  2 #include<stdio.h>
  3 #include<stdlib.h>
  4 #include<string.h>
  5 #include<math.h>
  6 #include<iostream>
  7 #include<string>
  8 #include<algorithm>
  9 #include<vector>
 10 #include<queue>
 11 #include<stack>
 12 #include<map>
 13 using namespace std;
 14 #define LL __int64
 15 #define pii pair<int,int>
 16 #define Max(a,b) ((a)>(b)?(a):(b))
 17 #define Min(a,b) ((a)<(b)?(a):(b))
 18 #define mem(a,b) memset(a,b,sizeof(a))
 19 #define lson l,mid,rt<<1
 20 #define rson mid+1,r,rt<<1|1
 21 const int N=510000,INF=0x3f3f3f3f,MOD=1999997;
 22 const LL LLNF=0x3f3f3f3f3f3f3f3fLL;
 23 
 24 struct Node{
 25     int u,v;
 26 }e[N];
 27 struct Trie{
 28     Trie(){mem(next,0);val=0;}
 29     Trie *next[26];
 30     int val;
 31 };
 32 int num[N],first[N],next[N],vis[N];
 33 int cou,m;
 34 
 35 void adde(int a,int b)
 36 {
 37     e[m].u=a,e[m].v=b;
 38     next[m]=first[a],first[a]=m++;
 39     e[m].u=b,e[m].v=a;
 40     next[m]=first[b],first[b]=m++;
 41 }
 42 
 43 int bfs()
 44 {
 45     int i,u,v,k=1;
 46     queue<int> q;
 47     q.push(1);
 48     mem(vis,0);
 49     vis[1]=1;
 50     while(!q.empty()){
 51         u=q.front();q.pop();
 52         for(i=first[u];i!=-1;i=next[i]){
 53             if(!vis[e[i].v]){
 54                 vis[e[i].v]=1;
 55                 q.push(e[i].v);
 56                 k++;
 57             }
 58         }
 59     }
 60     return k==cou;
 61 }
 62 
 63 int build(Trie *rt,char *a)
 64 {
 65     if(*a==0){
 66         if(rt->val)num[rt->val]++;
 67         else {
 68             rt->val=++cou;
 69             num[cou]++;
 70         }
 71         return rt->val;
 72     }
 73     int idx=*a-'a';
 74     if(!rt->next[idx])
 75         rt->next[idx]=new Trie;
 76     return build(rt->next[idx],a+1);
 77 }
 78 
 79 int main()
 80 {
 81  //   freopen("in.txt","r",stdin);
 82     int i,j,ok,a,b;
 83     char s1[15],s2[15];
 84     Trie *head;
 85     head=new Trie;
 86     m=cou=0;
 87     mem(num,0);mem(first,-1);
 88     while(~scanf("%s%s",s1,s2)){
 89         a=build(head,s1);
 90         b=build(head,s2);
 91         adde(a,b);
 92     }
 93     ok=0;
 94     for(i=1;i<=cou;i++){
 95         if(num[i]&1)ok++;
 96         if(ok>2)break;
 97     }
 98     printf("%s\n",(!cou || ((ok==2 || ok==0) && bfs()))?"Possible":"Impossible");
 99     return 0;
100 }
原文地址:https://www.cnblogs.com/zhsl/p/2868190.html