题目中的条件比较细碎
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;
}