HDU 1116 Play on Words

链接地址: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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值