杭电OJ 1116(C++)

本题运用并查集和欧拉回路/通路。

#include <iostream>
#include <string>
#include <cstring>
using namespace std;

//每个字母的入度,出度,访问情况,所属集合的代表元素(所在树的根结点)
int in[30], out[30], vis[30], father[30];

//查找字母x所属集合的代表元素(所在树的根结点)
int find(int x)
{
	while (x != father[x])
		x = father[x];
	return x;
}

//将字母x和y所属的集合合并(合并两棵树)
void Union(int x, int y)
{
	int fx = find(x), fy = find(y);
	if (fx != fy)
		father[fx] = fy;
}

int main()
{
	int T;
	cin >> T;
	while (T--)
	{
		memset(in, 0, sizeof(in));
		memset(out, 0, sizeof(out));
		memset(vis, 0, sizeof(vis));
		int N;
		cin >> N;
		//建立26个字母的并查集
		for (int i = 0; i < 26; i++)
		{
			father[i] = i;
		}
		string s; //输入的单词
		int start, end; //输入单词的首字母、尾字母
		for (int i = 0; i < N; i++)
		{
			cin >> s;
			start = s[0] - 'a';
			end = s[s.length() - 1] - 'a';
			in[start]++; //首字母入度加1
			out[end]++; //尾字母出度加1
			Union(start, end); //合并首尾字母所在集合
			vis[start] = vis[end] = 1;
		}

		int cnt = 0; //26个字母所在集合的数量
		for (int i = 0; i < 26; i++)
		{
			if (vis[i] == 1 && father[i] == i)
				++cnt;
		}
		if (cnt > 1) //森林中树的个数大于1,图不连通
		{
			cout << "The door cannot be opened." << endl;
			continue;
		}
		int ans = 0; //所有字母中入度和出度不相等的数量
		int x = 0, y = 0; //入度大于出度的数量,出度大于入度的数量
		for (int i = 0; i < 26; i++)
		{
			if (vis[i] == 1 && in[i] != out[i])
			{
				++ans;
				if (in[i] == out[i] + 1)
					++x;
				else if (out[i] == in[i] + 1)
					++y;
			}
		}
		if (ans == 0) //所有字母入度等于出度,构成欧拉回路
			cout << "Ordering is possible." << endl;
		else if (ans == 2 && x == 1 && y == 1) //只有首尾入度不等于出度,构成欧拉通路
			cout << "Ordering is possible." << endl;
		else
			cout << "The door cannot be opened." << endl;
	}
	return 0;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值