代码参考:1034. Head of a Gang (30)-PAT甲级真题(图的遍历dfs)_柳婼 の blog-CSDN博客
#include<iostream>
#include<map>
#include<vector>
using namespace std;
int N, K;
map<string, int> sToi;
map<int, string> iTos;
int number = 1;
int relation[2001][2001] = { 0 };
int tt[2001] = { 0 };
int c = 1;
int isvisited[2001] = { 0 };
vector<int>ans;
map<string, int> result;
int getIndex(string in) {
if (sToi[in] == 0) {
sToi[in] = number;
iTos[number] = in;
number++;
}
return sToi[in];
}
void dfs(int i) {
for (int j = 1; j <= sToi.size(); j++) {
if (relation[i][j] !=0 && isvisited[j]==0) {
c++; isvisited[j] = 1;
ans.push_back(j);
dfs(j);
}
}
}
int main() {
cin >> N >> K;
for (int i = 1; i <= N; i++) {
string a, b; int t;
cin >> a >> b >> t;
int index1 = getIndex(a);
int index2 = getIndex(b);
tt[index1] += t;
tt[index2] += t;
relation[index1][index2] += t;
relation[index2][index1] += t;
}
for (int i = 1; i <= sToi.size(); i++) {
if (isvisited[i] == 0) {
isvisited[i] = 1;
ans.clear();
ans.push_back(i);
c = 1;
dfs(i);
if (c > 2) {
int m = tt[ans[0]]; int index = 0;
for (int j = 1; j < ans.size();j++) {
if (tt[ans[j]] > m) {
m = tt[ans[j]]; index = j;
}
}
int all = 0;
for (int i = 0; i < ans.size() - 1; i++) {
for (int j = i + 1; j < ans.size(); j++) {
all += relation[ans[i]][ans[j]];
}
}
if(all>K)
result[iTos[ans[index]]] = c;
}
}
}
cout << result.size() << endl;
for (auto it : result) {
cout << it.first << " " << it.second << endl;
}
return 0;
}