解法一:并查集

建立关系网络,用 dfs 实现并查集,统计人数和 weight 是否满足要求,最后按照名字的字典序排列输出。

  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. class Person {
  4. public:
  5. string name;
  6. int weight;
  7. bool vis;
  8. set<Person *> next;
  9. Person() {}
  10. Person(string name, int weight) : name(name), weight(weight), vis(false) {}
  11. };
  12. map<string, Person> gangMap;
  13. int cnt;
  14. int total;
  15. Person *gang;
  16. vector<pair<Person *, int>> ans;
  17. void dfs(Person &p) {
  18. ++cnt;
  19. total += p.weight;
  20. if (p.weight > gang->weight) {
  21. gang = &p;
  22. }
  23. p.vis = true;
  24. for (auto &it:p.next) {
  25. if (!it->vis) {
  26. dfs(*it);
  27. }
  28. }
  29. }
  30. bool cmp(pair<Person *, int> &o1, pair<Person *, int> &o2) {
  31. return o1.first->name < o2.first->name;
  32. }
  33. int main() {
  34. ios::sync_with_stdio(false);
  35. cin.tie(0);
  36. int N, K;
  37. cin >> N >> K;
  38. string name1, name2;
  39. int time;
  40. map<string, Person>::iterator res1, res2;
  41. for (int i = 0; i < N; ++i) {
  42. cin >> name1 >> name2 >> time;
  43. res1 = gangMap.find(name1);
  44. if (res1 == gangMap.end()) {
  45. gangMap.emplace(name1, Person(name1, time));
  46. } else {
  47. res1->second.weight += time;
  48. }
  49. res2 = gangMap.find(name2);
  50. if (res2 == gangMap.end()) {
  51. gangMap.emplace(name2, Person(name2, time));
  52. } else {
  53. res2->second.weight += time;
  54. }
  55. res1 = gangMap.find(name1);
  56. res2 = gangMap.find(name2);
  57. res1->second.next.emplace(&res2->second);
  58. res2->second.next.emplace(&res1->second);
  59. }
  60. for (auto &it:gangMap) {
  61. if (!it.second.vis) {
  62. cnt = 0;
  63. total = 0;
  64. gang = &it.second;
  65. dfs(it.second);
  66. if (cnt > 2 && total / 2 > K) {
  67. ans.emplace_back(make_pair(gang, cnt));
  68. }
  69. }
  70. }
  71. sort(ans.begin(), ans.end(), cmp);
  72. cout << ans.size() << '\n';
  73. for (auto &it:ans) {
  74. cout << it.first->name << " " << it.second << '\n';
  75. }
  76. }