Colored Sticks
Time Limit: 5000MS Memory Limit: 128000K
Total Submissions: 22276 Accepted: 5884
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.
Source
The UofA Local 2000.10.14
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXN 5000100
#define MAXV 500100
int n;
struct Lnode{
int next[26];
int IsEnd;
}node[MAXN];
int nNode;
int ind[MAXV];
int father[MAXV];
int find(int cur){
if (cur == father[cur]) return cur;
return father[cur] = find(father[cur]);
}
int GetIndex(char *s){
int i, j, k, pre;
k = 0;
for (i = 0; s[i]; i++){
pre = k;
k = node[k].next[s[i] - 'a'];
if (k < 0){
memset(node[nNode].next, 0xff, sizeof(node[0].next));
node[nNode].IsEnd = 0;
node[pre].next[s[i] - 'a'] = nNode;
k = nNode++;
}
}
if (node[k].IsEnd == 0){
node[k].IsEnd = ++n;
ind[n] = 0;
father[n] = n;
}
return node[k].IsEnd;
}
int main(){
int i, j, k;
char sbg[15], sed[15];
memset(node[0].next, 0xff, sizeof(node[0].next));
node[0].IsEnd = 0;
nNode = 1;
n = 0;
while(scanf("%s %s", sbg, sed) != EOF){
i = GetIndex(sbg);
ind[i]++;
j = GetIndex(sed);
ind[j]++;
father[find(i)] = find(j);
}
k = (ind[1] & 1);
for (i = 2; i <= n; i++){
if (find(i) != find(i - 1)) break;
k += (ind[i] & 1);
}
if (i <= n || (k != 0 && k != 2)) printf("Impossible");
else printf("Possible");
return 0;
}
/*
判无向图有欧拉通路
1.度数为0或2
2.连通
开始图建错了...俩端标识的数特别大,以为只能拿木棒做顶点,
然后就纠结了...后来想离散化下不就好了...本来就要为每个颜色标号
一共有50W个端点,就有至多这么多种颜色嘛
*/