Colored Sticks
Time Limit: 5000MS | Memory Limit: 128000K | |
Total Submissions: 31585 | Accepted: 8353 |
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
妈蛋,坑,空数据输出Possible,看了讨论区才知道,,wa了好多次
ac代码
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
char a[110],b[110];
int pre[500050],dig[500050];
void init()
{
int i;
for(i=0;i<500050;i++)
{
pre[i]=i;
}
memset(dig,0,sizeof(dig));
}
typedef struct s
{
struct s *child[30];
int n;
}node,*Node;
Node root;
void insert(char *s,int n)
{
Node cur=NULL;
Node newnode=NULL;
int len=strlen(s),now;
cur=root;
for(int i=0;i<len;i++)
{
now=s[i]-'a';
if(cur->child[now]!=NULL)
{
cur=cur->child[now];
}
else
{
newnode=(Node)calloc(1,sizeof(node));
cur->child[now]=newnode;
cur=cur->child[now];
}
}
cur->n=n;
}
int seach(char *s)
{
int i,len=strlen(s);
Node cur=root;
int now;
for(i=0;i<len;i++)
{
now=s[i]-'a';
if(cur->child[now]!=NULL)
{
cur=cur->child[now];
}
else
return 0;
}
return cur->n;
}
int find(int x)
{
int r=x;
while(r!=pre[r])
r=pre[r];
int i=x,j;
while(pre[i]!=r)
{
j=i;
i=pre[i];
pre[j]=r;
}
return r;
}
void memge(int x,int y)
{
int fx,fy;
fx=find(x);
fy=find(y);
if(fx!=fy)
{
pre[fx]=fy;
}
}
int main()
{
int cot=0,i,j;
root=(Node)calloc(1,sizeof(node));
init();
while(scanf("%s%s",a,b)!=EOF)
{
int x,y;
x=seach(a);
y=seach(b);
if(x==0)
insert(a,x=++cot);
if(y==0)
insert(b,y=++cot);
dig[x]++;
dig[y]++;
memge(x,y);
}
int sum=0;
for(i=1;i<=cot;i++)
{
if(pre[i]==i)
sum++;
}
if(sum>1)
{
printf("Impossible\n");
}
else
{
int odd=0;
for(i=1;i<=cot;i++)
{
if(dig[i]&1)
odd++;
}
if(odd==0||odd==2)
printf("Possible\n");
else
printf("Impossible\n");
}
}