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.
解题报告和代码实现如下:
思路相当清晰
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- #include <iostream>
- #include <cstring>
- #include <stdlib.h>
- #include <stdio.h>
- #define MAX 500004
- using namespace std;
- char s1[15], s2[15];
-
-
-
-
-
-
- int degree[MAX];
- struct TreeNode
- {
- int ID;
- bool term;
- TreeNode* next[27];
- TreeNode()
- {
- ID = -1;
- term = false;
- int i;
- for(i = 0; i< 27; i++)
- next[i] = NULL;
- }
- }* root;
- int num = 0;
-
- int search(char* s, TreeNode* root)
- {
- TreeNode* p = root;
- if(p == NULL) return -1;
- int i = 0, l = strlen(s);
- for(i = 0; i< l; i++)
- {
- if(p->next[s[i] - 'a']== NULL) return -1;
- else p = p->next[s[i] - 'a'];
- }
- if(p->term == true) return p-> ID;
- else return -1;
- }
-
- int insert(char* s, TreeNode* root)
- {
- TreeNode* p = root;
- int t = search(s, root);
- if(t > 0) return t;
-
- int i = 0, l = strlen(s);
- for(; i< l; i++)
- {
- if(p->next[s[i] - 'a'] == NULL)
- p->next[s[i] - 'a'] = new TreeNode;
- p = p->next[s[i] - 'a'];
- }
- p->term = true;
- num ++;
- p->ID = num;
- return p->ID;
- }
-
-
-
-
-
- int parent[MAX];
- int rank[MAX];
-
- void intial()
- {
- int i;
- for(i = 0; i < MAX; i++)
- { parent[i] = i;
- rank[i] = 1;
- degree[i] = 0;
- }
- }
-
- int find(int x)
- {
- if(parent[x] != x)
- parent[x] = find(parent[x]);
- return parent[x];
- }
-
- void merge(int x, int y)
- {
- if(rank[x] > rank[y])
- parent[y] = x;
- else if(rank[y] < rank[x])
- parent[x] = y;
- else
- {
- rank[y] ++;
- parent[x] = y;
- }
- }
-
- int main()
- {
-
- root = new TreeNode;
- intial();
- while(scanf("%s %s", s1, s2) != EOF)
- {
-
- int id1 = insert(s1, root);
- int id2 = insert(s2, root);
- degree[id1] ++;
- degree[id2] ++;
-
-
- int gid1 = find(id1);
- int gid2 = find(id2);
- if(gid1 != gid2)
- {
- merge(gid1, gid2);
- }
- }
-
-
- int i ,j;
- int noood = 0;
- for(i = 1; i<= num; i++)
- {
-
- if(degree[i] % 2 == 1) noood ++;
- if(noood > 2)
- {
- cout << "Impossible" << endl;
- return 0;
- }
- }
-
-
- int gnum = parent[1];
- for(i = 1; i<= num; i++)
- {
-
- if(gnum != parent[i])
- {
- cout << "Impossible" << endl;
- return 0;
- }
- }
-
- cout << "Possible" << endl;
-
- return 0;
- }