Colored Sticks
Time Limit: 5000MS | Memory Limit: 128000K | |
Total Submissions: 33185 | Accepted: 8729 |
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.
问你字符串能不能欧拉回路。简单明了的题用到了三个知识点。。
首先要考虑的是数据范围,给出的范围过大用字典树hash为int,而后判断是不是欧拉回路(图连通且结点的度均为偶数或有两个奇数度
的点)。
AC代码:
#include "iostream"
#include "cstdio"
#include "cstring"
#include "algorithm"
using namespace std;
const int MAXN = 5e5 + 5;
int par[MAXN], deg[MAXN], ran[MAXN], n = 1;
struct node
{
/* data */
int id;
bool vis;
node *next[30];
node() {
id = 0;
vis = false;
for(int i = 0; i < 27; ++i)
next[i] = NULL;
}
}*root;
int hashint(char *s)
{
node *p = root;
int k;
while(*s != 0) {
k = *s - 'a';
if(p -> next[k] == NULL) p -> next[k] = new node();
p = p -> next[k];
s++;
}
if(!p -> vis) {
p -> id = n;
n++;
p -> vis = true;
return p -> id;
}
else return p -> id;
}
int find(int x)
{
if(x == par[x]) return x;
return par[x] = find(par[x]);
}
void merge(int x, int y)
{
if(ran[x] < ran[y]) par[x] = y;
else {
par[y] = x;
if(ran[x] == ran[y]) x++;
}
}
int main(int argc, char const *argv[])
{
char a[15], b[15];
root = new node();
for(int i = 1; i < MAXN; ++i)
par[i] = i;
while(scanf("%s%s", a, b) != EOF) {
int x = hashint(a), y = hashint(b);
deg[x]++, deg[y]++;
int fx = find(x), fy = find(y);
if(fx != fy) merge(fx, fy);
}
int tmp = find(1), num = 0;
for(int i = 1; i < n; ++i) {
if(find(i) != tmp) {
printf("Impossible\n");
return 0;
}
if(deg[i] % 2) num++;
if(num > 2) {
printf("Impossible\n");
return 0;
}
}
if(num == 1) printf("Impossible\n");
else printf("Possible\n");
return 0;
}