HDU 1116 Play on Words

来源:互联网 发布:詹姆斯五项数据第一 编辑:程序博客网 时间:2024/06/05 00:07
链接地址:http://acm.hdu.edu.cn/showproblem.php?pid=1116
简单的成语接龙变形题,欧拉路的基本题。
所谓欧拉路就是每个点的入度等于出度;
所谓半欧拉路就是起点的出度比入度大1,终点的入度比出度大1,其他点的入度等于出度。
将每个单词取出首字母和尾字母,转换为一条边,然后加入对应的连通分量中。如果这个字母出现过,visit数组标记为true。同时起点出度加1,终点入度加1。
首先,这个图必须是连通的,即根节点只有一个。
其次,判断是否为欧拉路或者是半欧拉路。
还有,这里要用到并查集的思想。
然后用start保存起点,end保存终点。

以下是我AC的代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <stack>
#include <vector>
#include <queue>
#include <set>
#include <cstdlib>
using namespace std;

int in[30];
int out[30];
int judge[30];
int visit[30];

int find(int x)
{
return x == judge[x] ? x : find(judge[x]);
}

void put(int x, int y)
{
int a, b;
a = find(x);
b = find(y);
if (a != b) judge[b] = a;
}

int main()
{
int n, T, s, start, end, inin, outout, root, p1, p2;
char str[1005];

scanf("%d", &T);
while (T--)
{
memset(in, 0, sizeof(in));
memset(out, 0, sizeof(out));
memset(visit, 0, sizeof(visit));
for (int i = 1; i < 30; i++)
{
judge[i] = i;
}
inin = outout = root = 0;
p1 = p2 = 1;
scanf("%d", &n);
for (int i = 0; i < n; i++)
{
scanf("%s", str);
s = strlen(str);
start = str[0] - 96;
end = str[s - 1] - 96;
visit[start] = 1;
visit[end] = 1;
out[start]++;
in[end]++;
put(start, end);
}
for (int i = 1; i < 30; i++)
{
if (visit[i])
{
if (judge[i] == i)
{
root++;
if (root > 1)
{
p1 = 0;
break;
}
}
if (in[i] != out[i])
{
if (in[i] - out[i] == 1) inin++;
else if (in[i] - out[i] == -1) outout++;
else p2 = 0;
}
}
}
if (p1 && p2 && inin < 2 && outout < 2) printf("Ordering is possible.\n");
else printf("The door cannot be opened.\n");
}
system("pause");

return 0;
}

0 0
原创粉丝点击