pat 1034 Head of a Gang (30分)

/*
没有按照顺序输出,导致测试点2、5错误
*/
#include <iostream>
#include <vector>
#include <map>
#include <algorithm>
using namespace std;

const int M = 10005;

int N, K;

struct Node {
    string name;
    int weight = 0;
    int relationWeight = 0;
    Node(string tname, int tweight) : name(tname), weight(tweight) {}
    Node() {}
} people[M];

bool visit[M];

vector<int> adj[M];     //邻接表       /*将adj[N]写成了adj(N)*/
map<string, int> mp1;        //姓名---编号
map<int, string> mp2;        //编号---姓名
int MaxWeight = -1;

void DFS(int sub, int& count, int& head, int& sumWeight) {
    visit[sub] = true;
    count ++;
    sumWeight += people[sub].relationWeight;
    if (people[sub].weight >= MaxWeight) {
        head = sub;
        MaxWeight = people[sub].weight;
    }
    for (int i = 0; i < adj[sub].size(); i ++) {
        if (visit[adj[sub][i]] == false)
            DFS(adj[sub][i], count, head, sumWeight);
    }
}
bool cmp(const pair<string, int>& a, const pair<string, int>& b) {
    return a.first < b.first;
}

int main() {
    cin >> N >> K;
    int k = 0;
    for (int i = 0; i < N; i ++) {
        string name1, name2;
        int Time;
        cin >> name1 >> name2 >> Time;
        //为name生成编号
        if (mp1.count(name1) == 0) {        
            mp1[name1] = k;
            mp2[k ++] = name1;
        }
        if (mp1.count(name2) == 0) {
            mp1[name2] = k;
            mp2[k ++] = name2;
        }
        //创建/更新人
        people[mp1[name1]].name = name1;
        people[mp1[name1]].weight += Time;
        people[mp1[name1]].relationWeight += Time;
        
        people[mp1[name2]].name = name2;
        people[mp1[name2]].weight += Time;
        
        if (count(adj[mp1[name1]].begin(), adj[mp1[name1]].end(), mp1[name2]) == 0) {
            adj[mp1[name1]].push_back(mp1[name2]);
        }
        if (count(adj[mp1[name2]].begin(), adj[mp1[name2]].end(), mp1[name1]) == 0) {
            adj[mp1[name2]].push_back(mp1[name1]);
        }
    }
    
    for (int i = 0; i < N; i ++) {
        visit[i] = false;
    }
    int sum = 0;

    vector<pair<string, int>> res;
    
    for (int i = 0; i < N; i ++) {
        if (mp2.count(i) == 0)  continue;
        int count = 0, head, sumWeight = 0, totalRelatioWeight = 0;
        if (visit[i] == false) {
            DFS(i, count, head, sumWeight);
        }
        if (sumWeight > K && count > 2) {
            sum ++;
            pair<string, int> p(people[head].name, count);
            res.push_back(p);
        }
        MaxWeight = -1;
    }
    
    sort(res.begin(), res.end(), cmp);
    cout << sum << endl;
    
    for (auto p : res) {
        cout << p.first << " " << p.second << endl;
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值