解法一:并查集
建立关系网络,用 dfs
实现并查集,统计人数和 weight
是否满足要求,最后按照名字的字典序排列输出。
#include <bits/stdc++.h>
using namespace std;
class Person {
public:
string name;
int weight;
bool vis;
set<Person *> next;
Person() {}
Person(string name, int weight) : name(name), weight(weight), vis(false) {}
};
map<string, Person> gangMap;
int cnt;
int total;
Person *gang;
vector<pair<Person *, int>> ans;
void dfs(Person &p) {
++cnt;
total += p.weight;
if (p.weight > gang->weight) {
gang = &p;
}
p.vis = true;
for (auto &it:p.next) {
if (!it->vis) {
dfs(*it);
}
}
}
bool cmp(pair<Person *, int> &o1, pair<Person *, int> &o2) {
return o1.first->name < o2.first->name;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int N, K;
cin >> N >> K;
string name1, name2;
int time;
map<string, Person>::iterator res1, res2;
for (int i = 0; i < N; ++i) {
cin >> name1 >> name2 >> time;
res1 = gangMap.find(name1);
if (res1 == gangMap.end()) {
gangMap.emplace(name1, Person(name1, time));
} else {
res1->second.weight += time;
}
res2 = gangMap.find(name2);
if (res2 == gangMap.end()) {
gangMap.emplace(name2, Person(name2, time));
} else {
res2->second.weight += time;
}
res1 = gangMap.find(name1);
res2 = gangMap.find(name2);
res1->second.next.emplace(&res2->second);
res2->second.next.emplace(&res1->second);
}
for (auto &it:gangMap) {
if (!it.second.vis) {
cnt = 0;
total = 0;
gang = &it.second;
dfs(it.second);
if (cnt > 2 && total / 2 > K) {
ans.emplace_back(make_pair(gang, cnt));
}
}
}
sort(ans.begin(), ans.end(), cmp);
cout << ans.size() << '\n';
for (auto &it:ans) {
cout << it.first->name << " " << it.second << '\n';
}
}