1034. Head of a Gang (30)解题报告

#define _CRT_SECURE_NO_WARNINGS
#include <cstdio>
#include <cstdlib>
#include <map>
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

using namespace std;
#define N 3000
struct person {
    string name;
    int w, gang_weight, cnt;
};

int find(int s[], int elem);
void Union(int s[], int root1, int root2);
bool comp(person p1, person p2);
int main(void) {
    int n, k, i, s[N], weight, w[N] = { 0 }, cnt = 0;
    for (i = 0; i < N; i++) {
        s[i] = -1;
    }
    string s1, s2;
    map<string, int> mp;
    map<int, string> remp;
    map<int, person> gang_weight;
    map<int, person>::iterator it;
    scanf("%d %d", &n, &k);
    for (i = 0; i < n; i++) {
        cin >> s1 >> s2 >> weight;
        if (mp.find(s1) == mp.end()) {
            mp[s1] = cnt;
            remp[cnt] = s1;
            cnt++;
        }
        if (mp.find(s2) == mp.end()) {
            mp[s2] = cnt;
            remp[cnt] = s2;
            cnt++;
        }
        w[mp[s1]] += weight;
        w[mp[s2]] += weight;
        Union(s, mp[s1], mp[s2]);
    }
    for (i = 0; i < cnt; i++) {
        if (s[i] < 0) {
            gang_weight[i].gang_weight = 0;
            gang_weight[i].cnt = abs(s[i]);
            gang_weight[i].w = 0;
        }
    }
    for (i = 0; i < cnt; i++) {
        int tmp = find(s, i);
        gang_weight[tmp].gang_weight += w[i] / 2;
        if (gang_weight[tmp].w < w[i]) {
            gang_weight[tmp].name = remp[i];
            gang_weight[tmp].w = w[i];
        }
    }
    it = gang_weight.begin();
    vector<person> v;
    person tmp;
    for (; it != gang_weight.end(); it++) {
        if (it->second.gang_weight > k && it->second.cnt > 2) {
            tmp = it->second;
            v.push_back(tmp);
        }
    }
    sort(v.begin(), v.end(), comp);
    printf("%d\n", v.size());
    for (i = 0; i != v.size(); i++) {
        cout << v[i].name << ' ' << v[i].cnt << endl;
    }
    return 0;
}

int find(int s[], int elem) {
    if (s[elem] < 0) {
        return elem;
    }
    else {
        return s[elem] = find(s, s[elem]);
    }
}
void Union(int s[], int root1, int root2) {
    int r1, r2;
    r1 = find(s, root1);
    r2 = find(s, root2);
    if (r1 == r2) {
        return;
    }
    else if (s[r1] < s[r2]) {
        s[r1] += s[r2];
        s[r2] = r1;
    }
    else {
        s[r2] += s[r1];
        s[r1] = r2;
    }
    return;
}
bool comp(person p1, person p2) {
    return p1.name < p2.name;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值