Trie,又称单词查找树,是一种树形结构,用于保存大量的字符串。它的优点是:利用字符串的公共前缀来节约存储空间。它有3个基本性质:
1. 根结点不包含字符,除根结点外每一个结点都只包含一个字符。
2. 从根结点到某一结点,路径上经过的字符连接起来,为该结点对应的字符串。
3. 每个结点的所有子结点包含的字符都不相同。
7.1 Trie树
7.1.1 实例
PKU JudgeOnline, 2513, ColoredSticks.
7.1.2 问题描述
给定一些棍子,棍子的两端涂上两种颜色。问这些棍子能不能连成一条直线,使得连在一起的两根棍子的相邻一端颜色相同。
7.1.3 输入
bluered
redviolet
cyanblue
bluemagenta
magentacyan
7.1.4 输出
Possible
7.1.5 分析
这里是个无向图的欧拉通路问题。
由于颜色种类很多,首先需要使用Trie树来查找颜色对应的编号。然后通过并查集和度数来判断欧拉通路是否存在。
7.1.6 程序
#include<stdio.h>
#include<string.h>
#include<iostream>
using namespace std;
#define maxNum 500002
int p[maxNum];
int rank[maxNum];
void makeSet(int x)
{
p[x] = x;
rank[x] = 0;
}
int findSet(int x)
{
if(x != p[x])
{
p[x] = findSet(p[x]);
}
return p[x];
}
void link(int x, int y)
{
if(rank[x] > rank[y]){
p[y] = x;
}else{
p[x] = y;
if(rank[x] == rank[y])
{
rank[y] = rank[y] + 1;
}
}
}
void unionSet(int x, int y)
{
link(findSet(x), findSet(y));
}
struct trieNode {
int self;//保存了是第几个加入树中,如果没有加入树中,则为
int son[26];//指向儿子结点的位置
};
trieNode Trie[500002];
int trieTop;
int colorNum;
int trieSearch(char *key)
{
char *c;
int son;
int node;
node = 0;
c = key;
while(*c != NULL)
{
son = *c - 'a';
if(Trie[node].son[son] == 0)
{
return -1;
}
c++;
node = Trie[node].son[son];
}
return Trie[node].self;
}
int trieInsert(char *key)
{
char *c;
int son;
int node;
node = 0;
c = key;
while(*c != NULL){
son = *c - 'a';
if(Trie[node].son[son] == 0)
{
break;
}
c++;
node = Trie[node].son[son];
}
while(*c != NULL){
son = *c - 'a';
Trie[node].son[son] = trieTop;
trieTop++;
c++;
node = Trie[node].son[son];
}
if(Trie[node].self == 0)
{
Trie[node].self = colorNum;
}
return node;
}
int degree[500002];
int main()
{
int i, j;
char stick[11];
int oddNum;
int from, to;
int fail;
trieTop = 1;
colorNum = 0;
memset(Trie, 0, sizeof(Trie));
memset(degree, 0, sizeof(degree));
for(i = 1; i < 500002; i++){
makeSet(i);
}
while(scanf("%s", stick) != EOF)// && strcmp(stick, "#") != 0)
{
from = trieSearch(stick);
if(from <= 0)
{
colorNum++;
from = colorNum;
trieInsert(stick);
}
scanf("%s", stick);
to = trieSearch(stick);
if(to <= 0)
{
colorNum++;
to = colorNum;
trieInsert(stick);
}
degree[from]++;
degree[to]++;
if(findSet(from) != findSet(to))
unionSet(from, to);
}
fail = 0;
if(colorNum != 0)
{
for(i = 1; i <= colorNum; i++){
for(j = 1; j <= colorNum; j++){
if(findSet(i) != findSet(j))
{
fail = 1;
break;
}
}
if(fail == 1)
{
break;
}
}
oddNum = 0;
if(fail == 0)
{
for(i = 1; i <= colorNum; i++){
if(degree[i] % 2 != 0)
{
oddNum++;
if(oddNum > 2)
{
fail = 1;
break;
}
}
}
if(oddNum != 0&& oddNum != 2)
{
fail = 1;
}
}
}
if(fail == 0)
{
cout << "Possible" << endl;
}else{
cout << "Impossible" << endl;
}
return 1;
}
7.2 实例
PKU JudgeOnline, 2513, Colored Sticks.
本文章欢迎转载,请保留原始博客链接http://blog.youkuaiyun.com/fsdev/article