DFS:注意一点,因为图中可能有环,所以dfs的时候先加进去权重再将路径置为0,之后再判断vis是否要递归进去,因为ksum用的引用,先加上权重就保证了ksum是都加进去了,如果是环的话,重复节点的那个vis不会dfs进去,只做了加法
#include<iostream>
#include<algorithm>
#include<map>
#include<string>
using namespace std;
const int maxv = 2e3 + 10;
const int INF = 1e8 + 10;
int n, k, cnt;
int G[maxv][maxv];
bool vis[maxv] = { false };
map<string, int>strtoint;
string intostr[maxv];
int weight[maxv];
int getnum(string name)
{
if (strtoint.find(name) == strtoint.end())
{
strtoint[name] = cnt;
intostr[cnt] = name;
return cnt++;
}
else return strtoint[name];
}
void DFS(int v,int &ksum,int &head,int &c)
{
vis[v] = true;
c++;
if (weight[v] > weight[head])head = v;
for (int i = 0; i < cnt; i++)
{
if (G[v][i] > 0)
{
ksum += G[v][i];
G[v][i] = G[i][v] = 0;
if (!vis[i])DFS(i, ksum, head, c);
}
}
}
map<string, int>gang;
int main()
{
scanf("%d%d", &n, &k);
for (int i = 0; i < maxv; i++)
for (int j = 0; j < maxv; j++)G[i][j] = 0;
for (int i = 0; i < n; i++)
{
string name1, name2;
int t;
cin >> name1 >> name2 >> t;
int v = getnum(name1);
int u = getnum(name2);
weight[v] += t;
weight[u] += t;
G[v][u] += t;
G[u][v] = G[v][u];
}
int gangcnt = 0;
for (int i = 0; i < cnt; i++)
{
if (!vis[i])
{
int ksum = 0, head = i, c = 0;
DFS(i, ksum, head, c);
if (ksum > k&&c>2)
{
gang[intostr[head]] = c;
}
}
}
printf("%d\n", gang.size());
for (auto it = gang.begin(); it != gang.end(); it++)
cout << it->first << " " << it->second << endl;
return 0;
}