PAT (Advanced Level) Practice 1158——并查集

题目传送门

题目中的条件比较细碎
suspect需要满足以下所有条件

  • 给多于K不同的人打过短电话
  • 不同的人打短电话收到回拨的比例不高于20%
  • 短电话指两人的总通话时长不超过5分钟
  • 如果suspect A和suspect B之间互相通信,那么A和B属于一个团伙

判断suspects是否属于一个团伙,可以使用并查集或者dfs
这里我选择了代码比较简单但是我并不熟悉的并查集
如果两个suspects之间存在会话,则将两者合并为一个集合
注意在选择并查集father的时候需要选择编号较小的那一个
按照father输出答案即可

#include<iostream>
#include<cstdio>
#include<cstdlib>
using namespace std;

const int N = 1010;
int K, n, m;
int mp[N][N] = { 0 };
int tot_call[N],back_call[N];
int suspect[N], cnt = 0;
int fa[N];
int ans[N][N] = { 0 };

int find(int x) {
	if (fa[x] != x) fa[x] = find(fa[x]);
	return fa[x];
}

int main()
{
	scanf("%d%d%d", &K, &n, &m);
	for (int i = 1; i <= m; ++i) {
		int x, y, t;
		scanf("%d%d%d",&x,&y,&t);
		mp[x][y] += t;
	}
	for (int i = 1; i <= n; ++i) {
		//total different short calls
		tot_call[i] = 0; 
		//call back
		back_call[i] = 0;
		for (int j = 1; j <= n; ++j) {
			//short calls
			if (mp[i][j] > 0 && mp[i][j] <= 5) {
				tot_call[i]++;
				//back of the short calls
				if (mp[j][i]) back_call[i]++;
			}
		}
		if (tot_call[i] > K && back_call[i] * 5 <= tot_call[i]) {
			//suspect
			cnt++;
			suspect[cnt] = i;
		}
	}
	if (!cnt) {
		printf("None");
		return 0;
	}
	for (int i = 1; i <= cnt; ++i) fa[suspect[i]] = suspect[i];
	for (int i = 1; i <= cnt; ++i) {
		for (int j = i+1; j <= cnt; ++j) {
			int x = suspect[i];
			int y = suspect[j];
			if (mp[x][y] && mp[y][x])   //have conversation
			{
				int f1 = find(x);
				int f2 = find(y);
				if (f1 != f2) {
					if (f1 < f2) swap(f1, f2);
					//choose the smaller one as the father
					fa[f1] = f2;   
				} 
			}
		}
	}
	for (int i = 1; i <= cnt; ++i) {
		int f = find(suspect[i]);
		ans[f][0]++;
		ans[f][ans[f][0]] = suspect[i];
	}
	for (int i=1;i<=n;++i) 
		if (ans[i][0]) {
			for (int j = 1; j < ans[i][0]; ++j)
				printf("%d ",ans[i][j]);
			printf("%d\n", ans[i][ans[i][0]]);
		}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值