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.
就是给n根木棒,木棒两端都有颜色,判断能不能把木棒合并成一条,接触的木棒端必须是相同颜色的。
给定一些木棒,木棒两端都涂上颜色,求是否能将木棒首尾相接,连成一条直线,要求不同木棒相接的一边必须是相同颜色的
字典树是给每个颜色一个编号。
然后就是判断了:
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<iostream>
using namespace std ;
const int maxn = 26 ;
const int maxm = 521521 ;
int fa[maxm],deg[maxm];
int ch[maxm][maxn] ;
int vis[maxm] ;
int cnt = 0 ;
struct Trie
{
int sz ;//节点总数
void TTrie()//初始时只有一个根节点
{
sz = 1 ;
memset(ch[0],0,sizeof(ch[0])) ;
}
int idx(char c)
{
return c-'a'; //字符c的编号
}
//插入字符串s,附加信息为v,注意v必须为非0,因为0代表“本节点不是单词节点”
int insert(char *s)
{
int u = 0 ,n = strlen(s) ;
for(int i = 0 ; i < n ; i++)
{
int c = idx(s[i]) ;
if(!ch[u][c])//节点不存在
{
memset(ch[sz],0,sizeof(ch[sz]));
vis[sz] = 0 ;//中间节点的附加信息为0
ch[u][c] = sz++ ;//新建节点
}
u = ch[u][c] ;//往下走
}
if(!vis[u])
vis[u] = ++cnt ;
return vis[u] ;
//vis[u] = v ; //字符串中的最后一个字符的附件信息为v
}
};
int findset(int x)
{
return fa[x]==-1? x : fa[x]=findset(fa[x]);
}
void Init()
{
memset(deg,0,sizeof(deg)) ;
memset(fa,-1,sizeof(fa));
}
int main()
{
char a[100],b[100];
Trie trie;
Init();
trie.TTrie();
while(cin>>a>>b)
{
int u=trie.insert(a);
int v=trie.insert(b);
deg[u]++;
deg[v]++;
int fu=findset(u);
int fv=findset(v);
if(fu!=fv)
{
fa[fu]=fv;
}
}
int ans=0;
for(int i=1;i<=cnt;i++)
{
if(deg[i]%2==1)
{
ans++;
}
if(ans>2||findset(1)!=findset(i))
{
printf("Impossible\n") ;
return 0 ;
}
}
if(ans==1)
{
printf("Impossible\n") ;
}
else
{
printf("Possible\n");
}
}