# poj 2513 Colored Sticks 并查集+欧拉路

Colored Sticks
Time Limit: 5000MS Memory Limit: 128000K
Total Submissions: 38637 Accepted: 10111
Description

You are given a bunch of wooden sticks. Each endpoint of each stick is colored with some color. Is it possible to align the sticks in a straight line such that the colors of the endpoints that touch are of the same color?
Input

Input is a sequence of lines, each line contains two words, separated by spaces, giving the colors of the endpoints of one stick. A word is a sequence of lowercase letters no longer than 10 characters. There is no more than 250000 sticks.
Output

If the sticks can be aligned in the desired way, output a single line saying Possible, otherwise output Impossible.
Sample Input

blue red
red violet
cyan blue
blue magenta
magenta cyan
Sample Output

Possible
Hint

Huge input,scanf is recommended.
Source
【题解】

~(≧▽≦)/~啦啦啦

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define maxl 15
#define maxn 500005
using namespace std;
char x[maxl],y[maxl];
int n,m,tot,sum,fa[maxn],hsh[maxn];
struct chj{
int id;
char s[maxl];
bool operator<(const chj b)const{return strcmp(s,b.s)<0;}
}a[maxn];
inline int get(int x){return fa[x]==x?x:fa[x]=get(fa[x]);}
int main(){
freopen("2513.in","r",stdin);
freopen("2513.out","w",stdout);
while (~scanf("%s%s",x,y)){
n++;
a[++m].id=n;strcpy(a[m].s,x);
a[++m].id=n;strcpy(a[m].s,y);
}
sort(a+1,a+m+1);
for (int i=1;i<=n;i++) fa[i]=i;
int i=1;
while (i<=m){
int j=i+1;
hsh[++tot]=1;
while (j<=m&&strcmp(a[i].s,a[j].s)==0){
int fx=get(a[i].id),fy=get(a[j].id);
fa[fx]=fy;
hsh[tot]++;
j++;
}
i=j;
}
for (int i=1;i<=tot;i++) sum+=hsh[i]&1;
int fath=get(a[1].id);
for (int i=2;i<=m;i++)
if (get(a[i].id)!=fath){printf("Impossible\n");return 0;}
if (sum!=0&&sum!=2) printf("Impossible\n");else printf("Possible\n");
return 0;
}

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120