poj 1386 Play on Words(有向图欧拉路+并查集)

题目链接:http://poj.org/problem?id=1386

思路分析:该问题要求判断单词是否能连接成一条直线,转换为图论问题:将单词的首字母和尾字母看做一个点,每个单词描述了一条从首字母指向尾字母的有向边,

则则所有的单词构成了一个有向图,问题变为判断该有向图中是否存在一条欧拉路;有向图中存在欧拉路的两个充分必要条件为:该图是联通的并且所有的点的入度等于出度或者只存在两个点的入度与出度不等,一个点的入度=出度+1,另一个点的入度=出度-1;

代码如下:

#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std; const int MAX_N = ;
const int MAX_M = + ;
int fa[MAX_N], show[MAX_N];
int in[MAX_N], out[MAX_N];
int set_visited[MAX_N];
char str[MAX_M]; void Init()
{
for (int i = ; i < MAX_N; ++i)
fa[i] = i;
memset(in, , sizeof(in));
memset(out, , sizeof(out));
memset(show, , sizeof(show));
memset(set_visited, , sizeof(set_visited));
} int Find(int a)
{
if (fa[a] == a)
return a;
else
return fa[a] = Find(fa[a]);
} int Union(int a, int b)
{
int fa_a = Find(a);
int fa_b = Find(b); if (fa_a == fa_b)
return -;
if (fa_a > fa_b)
fa[fa_b] = fa_a;
else
fa[fa_a] = fa_b;
return ;
} int main()
{
int case_times, n, len; scanf("%d", &case_times);
while (case_times--)
{
scanf("%d", &n);
Init();
for (int i = ; i < n; ++i)
{
int l, r; scanf("%s", str);
len = strlen(str);
l = str[] - 'a';
r = str[len - ] - 'a';
in[l]++;
out[r]++;
show[l] = show[r] = ;
Union(l, r);
}
int set_count = ;
int not_equal = ;
int in_big_out = , out_big_in = ;
bool ok = true;
for (int i = ; i < MAX_N; ++i)
{
if (show[i])
{
int fa_i = Find(i);
if (set_visited[fa_i] == )
{
set_count++;
set_visited[fa_i] = ;
}
if (set_count > )
{
ok = false;
break;
}
if (in[i] != out[i])
not_equal++;
if (in[i] == out[i] + )
in_big_out++;
if (in[i] + == out[i])
out_big_in++;
}
} if (!((not_equal == ) || (out_big_in == && in_big_out ==
&& in_big_out + out_big_in == not_equal)))
ok = false; if (ok)
printf("Ordering is possible.\n");
else
printf("The door cannot be opened.\n");
}
return ;
}
上一篇:Nginx+Tomcat的服务器端环境配置详解


下一篇:Windows7中安装内存与可用内存不一致的解决办法