【牛客网】KY138 Head of a Gang

在这里插入图片描述
利用并查集的思路将数据分成多个连通子图,并输出根结点即其权重:

#include<iostream>
#include<cstdio>
#include<string>
#include<map>

using namespace std;

const int N = 1000 + 10;

struct Relationship{
    string name1, name2;
    int time;
};
Relationship arr[N];
map<string, string> father;  //每个成员的父亲结点
map<string, int> weight;  //每个成员花费的总时间
map<string, int> sum;  //用于记录一个团体的总时间
map<string, int> count;  //用于记录一个团体的人数
map<string, int> ans;  //最终结果

string Find(string x){
    while(x != father[x]) x = father[x];
    return x;
}

void Union(string x, string y){
    string root1 = Find(x);
    string root2 = Find(y);
    if(root1 != root2){
        if(weight[root1] > weight[root2]){
            father[root2] = root1;
        }else{
            father[root1] = root2;
        }
    }
}

void Clear(){
    father.clear();
    weight.clear();
    sum.clear();
    count.clear();
    ans.clear();
}

int main(){
    int n, k;
    while(scanf("%d%d", &n, &k) != EOF){
        Clear();
        for(int i = 0; i < n; i++){
            cin>>arr[i].name1>>arr[i].name2>>arr[i].time;
            weight[arr[i].name1] += arr[i].time;
            weight[arr[i].name2] += arr[i].time;
            father[arr[i].name1] = arr[i].name1;
            father[arr[i].name2] = arr[i].name2;
        }
        for(int i = 0; i < n; i++) Union(arr[i].name1, arr[i].name2);
        for(map<string, string>::iterator it = father.begin(); it != father.end(); it++){
            string root = Find(it->first);
            sum[root] += weight[it->first];
            count[root]++;
        }
        for(map<string, int>::iterator it = count.begin(); it != count.end(); it++){
            if(sum[it->first] > k * 2 && it->second > 2)  //因为每个权重都加了两次,所以判断2k
                ans[it->first] = it->second;
        }
        cout<<ans.size()<<endl;
        for(map<string, int>::iterator it = ans.begin(); it != ans.end(); it++){
            cout<<it->first<<" "<<it->second<<endl;
        }
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

花无凋零之时

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值