PAT 1034

来源:互联网 发布:淘宝还能兑换虾米会员 编辑:程序博客网 时间:2024/06/05 06:08
#include #include #include #define inf 9999using namespace std;int N, K;map gang,res;map  weight;map gangs;set ans;string findHead(string id){if (gang[id] == "") gang[id] = id;if (gang[id] == id) return id;string head = findHead(gang[id]),temp = id;while (gang[temp] != temp) {string next = gang[temp];gang[temp] = head;temp = next;}return head;}void join(string a, string b){gang[findHead(a)] = findHead(b);}int main(){cin >> N >> K;for (int i = 0; i < N; i++) {string temp1, temp2;int temp3;cin >> temp1 >> temp2 >> temp3;join(temp1, temp2);weight[temp1] += temp3;weight[temp2] += temp3;}for (auto it : gang) {gangs[findHead(it.first)][0] = 0;gangs[gang[it.first]][1] = 0;}for (auto it : weight) {gangs[gang[it.first]][0] += 1;gangs[gang[it.first]][1] += it.second;}for (auto it : gangs){if (it.second[0] > 2 && it.second[1] > K * 2) {res[it.first] = "has";}}weight[""] = inf;for (auto it : weight){if (it.second > weight[res[gang[it.first]]]) {res[gang[it.first]] = it.first;}}for (auto it : res) {if (it.second != "") ans.insert(it.second);}cout << ans.size() << endl;for (auto it : ans) {cout << it << ' ' << gangs[gang[it]][0] << endl;}return 0;}