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?
【题目分析】
这道题还是比较综合的,hash用map太慢,用普通的trie树节点过多,左儿子、右兄弟又太慢。于是遇到了这种带指针的trie,比较简单而且方便。
人生第一份带指针的代码
【代码】
#include <cstdio>
#include <cstring>
int f[500001],rank[500001],deg[500001],n;
struct trie
{
int color;
trie *next[26];
trie()
{
color=0;
memset(next,0,sizeof (next));
}
}*root;
int insert(trie *p,char str[])
{
int i;
for (i=0;str[i]!='\0';++i)
{
int s=str[i]-'a';
if (p->next[s]==NULL) p->next[s]=new trie;
p=p->next[s];
if (str[i+1]=='\0')
{
if (p->color==0) p->color=++n;
deg[p->color]++;
}
}
return p->color;
}
inline void init()
{for (int i=1;i<=50000;++i) f[i]=i;}
inline int gf(int k)
{
if (f[k]==k) return k;
else return f[k]=gf(f[k]);
}
inline void un(int a,int b)
{
int fa=gf(a),fb=gf(b);
if (fa==fb) return ;
f[fa]=fb;
}
inline void read()
{
char s1[11],s2[11];
int x,y;
n=0,root=new trie;
init();
while (~scanf("%s%s",s1,s2))
{
x=insert(root,s1);
y=insert(root,s2);
un(x,y);
}
}
inline bool cal()
{
int flag=0;
for (int i=1;i<=n;++i)
{
if (flag&&f[i]==i) return false;
if (f[i]==i) flag=1;
}
int x=0;
for (int i=1;i<=n;++i) if (deg[i]%2) x++;
if (x==0||x==2) return true;
return false;
}
int main()
{
read();
if (cal()) printf("Possible\n");
else printf("Impossible\n");
}