标签:
题目链接:http://poj.org/problem?id=1386
思路分析:该问题要求判断单词是否能连接成一条直线,转换为图论问题:将单词的首字母和尾字母看做一个点,每个单词描述了一条从首字母指向尾字母的有向边,
则则所有的单词构成了一个有向图,问题变为判断该有向图中是否存在一条欧拉路;有向图中存在欧拉路的两个充分必要条件为:该图是联通的并且所有的点的入度等于出度或者只存在两个点的入度与出度不等,一个点的入度=出度+1,另一个点的入度=出度-1;
代码如下:
#include <cstdio> #include <cstring> #include <iostream> using namespace std; const int MAX_N = 30; const int MAX_M = 1000 + 10; 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 = 0; i < MAX_N; ++i) fa[i] = i; memset(in, 0, sizeof(in)); memset(out, 0, sizeof(out)); memset(show, 0, sizeof(show)); memset(set_visited, 0, 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 -1; if (fa_a > fa_b) fa[fa_b] = fa_a; else fa[fa_a] = fa_b; return 1; } int main() { int case_times, n, len; scanf("%d", &case_times); while (case_times--) { scanf("%d", &n); Init(); for (int i = 0; i < n; ++i) { int l, r; scanf("%s", str); len = strlen(str); l = str[0] - ‘a‘; r = str[len - 1] - ‘a‘; in[l]++; out[r]++; show[l] = show[r] = 1; Union(l, r); } int set_count = 0; int not_equal = 0; int in_big_out = 0, out_big_in = 0; bool ok = true; for (int i = 0; i < MAX_N; ++i) { if (show[i]) { int fa_i = Find(i); if (set_visited[fa_i] == 0) { set_count++; set_visited[fa_i] = 1; } if (set_count > 1) { ok = false; break; } if (in[i] != out[i]) not_equal++; if (in[i] == out[i] + 1) in_big_out++; if (in[i] + 1 == out[i]) out_big_in++; } } if (!((not_equal == 0) || (out_big_in == 1 && in_big_out == 1 && 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 0; }
poj 1386 Play on Words(有向图欧拉路+并查集)
标签:
原文地址:http://www.cnblogs.com/tallisHe/p/4671992.html