#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;
}
1034. Head of a Gang (30)解题报告
最新推荐文章于 2022-03-15 11:52:03 发布