题目大意
- 给你许多木棒,木棒的两端有颜色。若一根木棒某一端的颜色和另一根木棒某一端的颜色相同,则可以把这两根木棒颜色相同的一端连在一起形成一根长木棒。问所有的木棒能否连成一根长木棒。
- 数据有很多行,每行两个长度不超过10个字符的字符串,表示一根木棒两个端点的颜色。
题解
- 一开始想用map水过,然并TLE。
- 后来知道本题要用Trie存储每种颜色,于是乎记录了每种颜色出现的次数。若存在0种或2种只出现一次的颜色,像欧拉路一样,说明可以,然并WA。
- 然后知道了要判断图是否连通,于是使用并查集维护图的连通性,同时用Trie树记录字符串的编号。一次读入一行,即一根木棒两端的颜色,在Tire树中查询字符串是否存在。若存在,返回其编号;若不存在,则分配给该字符串一个新编号,并插入到Tire树中。得到编号后,把这两个编号合并到一个集合中。判断时,要判断每个点的度,即是否存在欧拉路;还要判断是否是连通图,即每个点在并查集中的祖先是否相同。
- 然后提交,并RE,原来数组开小了,因为不敢写指针。
- 改大数组后再交,WA。
- 再查错,发现记录点的度数的数组只开在那里,并没有任何修改,然后……
- 改过来以后,再交,WA。
- 静态查错无果,迷茫中……
- 然后上了趟厕所,回来一看,插入过程中把==打成了!=,真是中国好样例!
/*
blue red
red violet
cyan blue
blue magenta
magenta cyan
*/ - 改过来后,终于AC。
- Code
#include <cstdio>
#include <algorithm>
#include <cstring>
#define K 26
#define N 1000000
#define nil 0
#define root 0
using namespace std;
int sz, ch[N][K], ans, tot, val[N];
char str[2][K];
int fa[N], deg[N];
inline int find(int x) { return x == fa[x] ? x : find(fa[x]); }
inline int idx(char c) { return c - 'a'; }
inline void prepare()
{
sz = 1;
memset(ch[0], 0, sizeof(ch[0]));
memset(val, 0, sizeof(val));
}
void insert(char *s)
{
int u = root, n = strlen(s), c;
for(int i = 0; i < n; ++i)
{
c = idx(s[i]);
if(ch[u][c] == nil)
{
memset(ch[sz], 0, sizeof(ch[sz]));
ch[u][c] = sz++;
}
u = ch[u][c];
}
val[u] = ++tot;
}
inline int find(char *s)
{
int u = root, n = strlen(s), c;
for(int i = 0; i < n; ++i)
{
c = idx(s[i]);
if(ch[u][c] == nil) return nil;
u = ch[u][c];
}
return val[u];
}
bool check()
{
int odd = 0;
for(int i = 1; i <= tot; ++i)
{
if((deg[i] & 1) != 0) ++odd;
}
if(odd != 0 && odd != 2) return false;
for(int i = 2, j = find(1); i <= tot; ++i)
{
if(j != find(i)) return false;
}
return true;
}
int main()
{
prepare();
memset(deg, 0, sizeof(deg));
for(int i = 1; i < N; ++i) fa[i] = i;
ans = tot = 0;
int x, y;
while(scanf("%s%s", str[0], str[1]) == 2)
{
x = find(str[0]);
if(x == nil)
{
insert(str[0]);
x = tot;
}
y = find(str[1]);
if(y == nil)
{
insert(str[1]);
y = tot;
}
++deg[x]; ++deg[y];
if(find(x) != find(y)) fa[find(x)] = find(y);
}
if(check()) puts("Possible");
else puts("Impossible");
return 0;
}