Colored Sticks
Time Limit: 5000MS | Memory Limit: 128000K | |
Total Submissions: 39395 | Accepted: 10273 |
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
题意给你许多木棍,木棍的两端有颜色,2根端点颜色相同的木棍可以接起来,如果给定的所有木棍可以合成一根则输出
Possible else Impossible。
给定的木棍两边是字符串表示的,所以需要转化成数字,用map会超时=-=
所以要用字典树转化每个端点代表的数字,形成 端点a->b ,b->a 的无向图
转化成数字之后需要判断能否合成:
1,每根端点都能跟其他所有端点有联系 (并查集)
2,所有端点构成一个环或者一条通路 (欧拉回路)
两个条件都满足则成立 。
ac代码
#include <iostream>
#include <stdio.h>
#include <vector>
#include <algorithm>
#include <map>
#include <stdlib.h>
#include <string.h>
#include <sstream>
#include <math.h>
using namespace std;
int pre[500005];
int in[500005];
int digit;
struct len{
int num;
int flag;
struct len *next[27];
len(){
flag=0;
memset(next,0,sizeof(next));
}
}root;
int insert(char *s){
struct len *p=&root;
int length=strlen(s);
for(int i=0;i<length;i++){
int index=s[i]-'a';
if(p->next[index]==NULL){
p->next[index]=new struct len;
}
p=p->next[index];
}
if(p->flag!=1){
p->flag=1;
p->num=digit++;
return p->num;
}
else {
return p->num;
}
}
int find(int x){
int j=x;
while(j!=pre[j])j=pre[j];
int i=x,k;
while(pre[i]!=j){
k=pre[i];
pre[i]=j;
i=k;
}
return j;
}
void add(int x,int y){
int xx=find(x),yy=find(y);
if(xx!=yy){
pre[xx]=yy;
}
}
int main()
{
for(int i=1;i<=500001;i++)pre[i]=i;
char s1[15],s2[15];
digit=0;
memset(in,0,sizeof(in));
while(scanf("%s%s",s1,s2)!=EOF){
int t1=insert(s1),t2=insert(s2);
add(t1,t2);
in[t1]++;
in[t2]++;
}
int end=find(0),number=0;
if(in[0]%2)number++;
//for(int i=0;i<digit;i++)cout<<pre[i]<<'*';
for(int i=1;i<digit;i++){
if(find(i)!=end){
printf("Impossible\n");
return 0;
}
if(in[i]%2)number++;
}
if(number==0||number==2)printf("Possible\n");
else printf("Impossible\n");
}