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.
题意:有多个木棒,每个木棒两端都染上一种颜色,两个木棒相接触的两端的颜色必须是一样的,输入多行,每行两个单词,描述该木棒两端的颜色,问这些木棒能不能连成一条线。
思路:该题考察的方面太多了。
1.首先要输入的信息转换成图,观察该图是不是欧拉图,判断是否为欧拉图要具备两个条件:一是,该图是不是连通图,可用并查集来判断;二是,如果该图的奇数度的点有0个或2两个该图才会是欧拉图。
2.如何将信息转换成图?因为该题输入的是字符串,所以要把这些字符串转换成相应的整数才能建图,那么这可以用字典树来实现。
Sample Input
blue red red violet cyan blue blue magenta magenta cyan
Sample Output
Possible
Hint
Huge input,scanf is recommended.
#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <queue>
#define MAX 500005
using namespace std;
char s[20],t[20];
int ch[MAX][30]; //存图
int value[MAX]; //记录字符串的编号信息
int pre[MAX];
int angle[MAX],cnt,sizes;
void init()
{
for(int i=0; i<MAX; i++) //用以并查集
pre[i]=i;
memset(ch[0],0,sizeof(ch[0]));
memset(value,0,sizeof(value));
memset(angle,0,sizeof(angle)); //清空所有点的度数
cnt=0; //计数端点个数,刚开始为0
sizes=1; //记录字母即节点的编号
}
void inset(char *st) //插入字符串
{
int n=0,len=strlen(st);
for(int i=0; i<len; i++)
{
int c=st[i]-'a';
if(!ch[n][c]) //如果该字母不存在
{
memset(ch[sizes],0,sizeof(ch[sizes])); //清空sizes这一层的字母
ch[n][c]=sizes++; //插入字母
}
n=ch[n][c];
}
value[n]=++cnt;
}
int serch(char *st) //查找字符串
{
int n=0,len=strlen(st);
for(int i=0; i<len; i++)
{
int c=st[i]-'a';
if(!ch[n][c]) //如果不存在就插入
inset(st);
n=ch[n][c];
}
return value[n];
}
int Find(int x) //寻找祖先编号
{
int r,j,k;
r=x;
while(r!=pre[r])
r=pre[r];
k=x;
while(k!=r)
{
j=pre[k];
pre[k]=r;
k=j;
}
return r;
}
int main()
{
//freopen("lalala.text","r",stdin);
int a,b,fx,fy;
init();
while(~scanf("%s %s",s,t))
{
a=serch(s); //将字符串s转换成整数编号
angle[a]++; //编号为a的度数++
b=serch(t);
angle[b]++;
fx=Find(a);
fy=Find(b);
if(fx!=fy)
pre[fx]=fy;
}
int sum=0,odd=0;
for(int i=1; i<=cnt; i++)
if(pre[i]==i)
sum++;
for(int i=1; i<=cnt; i++)
if(angle[i]%2!=0)
odd++;
if((sum==1||sum==cnt)&&(odd==0||odd==2)) //如果不加sum==cnt会wa,因为如果端点数为0那么结果也是Possible(poj就是那么坑233333333
printf("Possible\n");
else
printf("Impossible\n");
return 0;
}