解法是参考的《算法笔记》,在逐渐学习stl中
#include <iostream>
#include <cstdio>
#include <map>
#include <string>
using namespace std;
const int maxn = 2010;
map<int,string>numTostr;
map<string ,int>strTOnum;
map<string,int>Gang;
int G[maxn][maxn] = {0};
int weight[maxn] = {0};
int n,k,numPerson = 0;
bool vis[maxn] = {false};
void dfs(int i,int &head,int &num,int &totalValue)
{
vis[i] = true;
num++;
if(weight[i]>weight[head])
head = i;
for(int j = 0;j<numPerson;j++)
{
if(G[i][j]>0)
{
totalValue +=G[i][j];
G[i][j] = G[j][i] = 0;
if(vis[j]== false)
dfs(j,head,num,totalValue);
}
}
}
void countBlock()
{
for(int i = 0;i<numPerson;i++)
{
if(vis[i]==false)
{
int num = 0;
int head = i;
int totalValue =0;
dfs(i,head,num,totalValue);
if(num>2 && totalValue>k)
Gang[numTostr[head]] = num;
}
}
}
int change(string str)
{
if(strTOnum.find(str)!=strTOnum.end())
return strTOnum[str];
else
{
strTOnum[str] = numPerson;
numTostr[numPerson] = str;
return numPerson++;
}
}
int main()
{
int w;
string str1,str2;
scanf("%d %d",&n,&k);
for(int i = 0;i<n;i++)
{
cin>>str1>>str2>>w;
int id1 = change(str1);
int id2 = change(str2);
weight[id1]+=w;
weight[id2]+=w;
G[id1][id2]+=w;
G[id2][id1]+=w;
}
countBlock();
printf("%d\n",Gang.size());
map<string,int>::iterator p;
for(p = Gang.begin();p!=Gang.end();p++)
{
cout<<p->first<<" "<<p->second<<endl;
}
return 0;
}