Colored Sticks
Time Limit: 5000MS | Memory Limit: 128000K | |
Total Submissions: 35039 | Accepted: 9155 |
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.
这个题就是说给你一些棒,然后每个棒的端点有一种颜色,问你能不能确保连接处颜色相的情况下把这些棒全部连起来。类似于七桥问题,只要确保度数为奇数的点的个数为0或者2个,并且是连通的的就可以了。
这里的难点就是要把字符串映射上编号,用map表示超时。。。。。。这数据专门卡的看样子,那就只好敲个字典树辣╮(╯▽╰)╭
一开始没看懂题意,以为是搜索,看看能不能连接起来尾部跟头部颜色相同了QAQ,自己英语好渣啊。
#include <iostream>
#include <stdio.h>
#include <cstring>
#include <string>
#include <cmath>
#include <algorithm>
#include <queue>
#include <map>
#include <vector>
using namespace std;
const int MAXN=500000;
struct node
{
int flag;
int next[26];
}nodes[MAXN];
int top,cnt;
int newnodes()
{
memset(nodes[top].next,-1,sizeof(nodes[top].next));
nodes[top].flag=0;
return top++;
}
int add(int root,char *s)
{
if(!(*s))
{
if(!nodes[root].flag)nodes[root].flag=++cnt;
return nodes[root].flag;
}
int t=*s-'a';
if(nodes[root].next[t]==-1)
{
nodes[root].next[t]=newnodes();
}
return add(nodes[root].next[t],s+1);
}
int pre[MAXN];
int du[MAXN];
int findx(int x)
{
int r=x;
while(r!=pre[r])r=pre[r];
int k=x;
while(pre[k]!=r)
{
x=pre[k];
pre[k]=r;
k=x;
}
return r;
}
void he(int x,int y)
{
int fx=findx(x);
int fy=findx(y);
if(fx!=fy)pre[fy]=fx;
}
char s1[30],s2[30];
int main()
{
int k1,k2;
int i;
top=cnt=0;
for(i=1;i<=MAXN;++i)pre[i]=i;
int root=newnodes();
while(~scanf("%s%s",s1,s2))
{
k1=add(root,s1);
k2=add(root,s2);
du[k1]++;
du[k2]++;
he(k1,k2);
}
int flag=1;
int sum=0;
for(i=1;i<=cnt;++i)if(pre[i]==i)sum++;
if(sum>1)
{
flag=0;
printf("Impossible\n");
}
if(flag)
{
sum=0;
for(i=1;i<=cnt;++i)if(du[i]%2)sum++;
if(sum!=0&&sum!=2)
{
flag=0;
printf("Impossible\n");
}
}
if(flag)printf("Possible\n");
return 0;
}