ACM: trie树 poj 2513
来源:互联网 发布:mac安装jdk 编辑:程序博客网 时间:2024/06/05 10:09
Colored Sticks
DescriptionYou are given a bunch of woodensticks. Each endpoint of each stick is colored with some color. Isit possible to align the sticks in a straight line such that thecolors 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 thecolors of the endpoints of one stick. A word is a sequence oflowercase letters no longer than 10 characters. There is no morethan 250000 sticks.
Output
If the sticks can be aligned inthe desired way, output a single line saying Possible, otherwiseoutput Impossible.
Sample Input
blue red
red violet
cyan blue
blue magenta
magenta cyan
Sample Output
Possible
题意: 给你一捆木头, 木头两端是有颜色, 现在要求将所有的木头首尾相接, 但是相接的端口要去
颜色一样.
解题思路:
1. trie树: 利用串的公共前缀来节约内存, 加快检索速度.
性质:
1). 根节点不包含字母, 除了根节点外每一个节点都仅包含一个字符.
2). 从根到某一节点, 路径上结果的字母依次连起来就是一个字母序列,就是一个串.
3). 每个节点的所有子节点的字母都不相同.
实现方法:
每个节点设置三个域: id, flag, next[26]
id域用来保存字母, flag域来标记到当前节点是否形成一个串, next[26]下一个节点指针域.
如图:
2. 题目要求木头首尾相接, 可以联想到blue-red -> red-cyan -> cyan-magenta -> magenta-blue
很像一条路径, 欧拉回路.无向欧拉: 每个节点的度%2 == 0或者有且仅有2个点的度数为奇数.
当然欧拉路采用是并查集的压缩路径
3. 欧拉路的判断 + trie树的结构查找题目就解决了.
代码:
#include <cstdio>
#include <iostream>
#include <cstring>
using namespace std;
#define MAX 500005
struct node
{
int id;
bool flag;
node *next[27];
}root;
int d[MAX], p[MAX];
int num;
char str1[11], str2[11];
void init()
{
num = 0;
for(int i = 0; i < MAX; ++i)
{
d[i] = 0;
p[i] = i;
}
root.flag = false;
root.id = 0;
memset(root.next, 0, sizeof(root.next));
}
int find(int x)
{
return p[x] == x ? x : (p[x] = find(p[x]));
}
void union_set(int x, int y)
{
x = find(x);
y = find(y);
if(x != y) p[y] = x;
}
int insert(char *str)
{
node *p = &root;
int len = strlen(str);
int temp;
for(int i = 0; i < len; ++i)
{