杭电1116——并差集+欧拉回路

杭电1116——并差集+欧拉回路

原题传送门并差集的简单解释大佬的并差集详解
解题思路:
这个题涉及了欧拉回路(因此这个题用的是有向图)的内容,如果你只有并差集的知识,是做不了这个题的。
其实欧拉回路就是名字高大上一点而已,内容还是很简单的。欧拉回路百度百科传送门,没听过的可以简单了解一下。

1、并差集
将所有能连接的单词都连起来,判断是不是都能连在一起。
2、欧拉回路

  • 欧拉路:有头有尾(一条链),有且仅有一个节点的入度比出度少一,有且仅有一个节点的入度比出度多一,其余节点的入度等于出度。
  • 欧拉回路:没头没尾(一个环),全部节点的入度等于出度。

写在最后:其实并差集适用的是无向图,有向图虽然也能用,但是条件比较苛刻,这个要注意。
ac代码:

# include <iostream>
# include <algorithm>
# include <cstdio>
# include <cstdlib>
# include <string>
# include <cstring>
# include <vector>
using namespace std;

typedef pair<int, int>P;
const int maxn = 30;
int id[maxn];
int vis[maxn];

int fin(int x) {
	return id[x] = id[x] == x ? x : fin(id[x]);
}
void meg(int x, int y) {//这里采用的原则的:谁小谁是父亲
	int a = fin(x);
	int b = fin(y);
	if (a < b) {
		id[a] = b;
	}
	else {
		id[b] = a;
	}
}
bool same(int x, int y) {
	return fin(x) == fin(y);
}

int main() {
	ios::sync_with_stdio(false);
	int T;
	cin >> T;
	while (T--) {
		for (int i = 0; i < maxn; i++) {
			id[i] = i;
		}
		memset(vis, 0, sizeof(vis));
		P p[26];//p[i]记录i的入度和出度
		for (auto i : p) {
			i.first = 0;
			i.second = 0;
		}
		//以上是重置(这点很重要,但是很容易被忽略)

		int n;
		cin >> n;
		string s;
		string ans = "Ordering is possible.";//初始化答案是yes
		for (int i = 0; i < n; i++) {
			cin >> s;
			int a = s[0] - 'a';
			int b = s.back() - 'a';
			vis[a] = 1;
			vis[b] = 1;
			if (a != b) {
				p[a].first++;
				p[b].second++;
				if (!same(a, b)) {
					meg(a, b);
				}
			}
		}
		int flag = 0;
		for (int i = 0; i < 26; i++) {//遍历vis和id数组,找出最上面的父亲有几个
			if (vis[i] == 1 && id[i] == i) {
				flag++;
			}
		}
		if (flag > 1) {//最上面的父亲只能有一个,如果flag大于1,说明不符合,ans记为no
			ans = "The door cannot be opened.";
		}
		int k = 0, t = 0;
		for (auto i : p) {//遍历p数组,判断是否符合欧拉回路
			if (abs(i.first - i.second) > 1) {//如果入度和出度的差值大于2,就一定不是欧拉回路,直接break
				ans = "The door cannot be opened.";
				break;
			}
			else if (i.first + 1 == i.second) {
				k++;//k记录差值为-1的个数
			}
			else if (i.first == i.second + 1) {
				t++;//t记录差值为1的个数
			}
		}
		if (k != t || k > 1 || t > 1) {//只要满足任何一个条件,就不是欧拉回路,ans记为no。
			ans = "The door cannot be opened.";
		}
		cout << ans << endl;
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值