#include <iostream>
#include <string>
#include <map>
using namespace std;
#define Max 2010 //一开始我把Max定义为1010结果出现了段错误。后来突然想到n条通话记录最多可以有2*n个人进行通话。
//所以需要把Max设置为2000以上
map<string,int> stringToInt;
map<int,string> intToString;
int Graph[Max][Max],visit[Max],weight[Max];
int numPerson = 1,head; //姓名编号从1开始
int StringToInt( string str ) //把姓名信息转换为编号
{
if( stringToInt.find(str) != stringToInt.end() ) //如果找到
{
return stringToInt[str];
}
else
{
stringToInt[str] = numPerson;
intToString[numPerson] = str; //为了后续把编号信息转换为姓名做准备
return numPerson++;
}
}
void DFS( int start,int &members,int &maxWeight,int &totalWeight) //members代表团伙中的人数。maxWeight为团伙中点权最大的(即头目)
{ //totalWeight为每个组的总边权
visit[start] = 1;
members++;
totalWeight += weight[start];
if( weight[start] > maxWeight ) //为了找到头目,需要比较点权
{
maxWeight = weight[start];
head = start;
}
for( int i=1;i<numPerson;++i )
{
if( visit[i] == 0 && Graph[start][i] != 0 )
{
DFS(i,members,maxWeight,totalWeight);
}
}
}
int main ()
{
int n,k;
cin>>n>>k;
for(int i=1;i<=n;++i)
{
string str1,str2;
int time;
cin>>str1>>str2>>time;
int id1 = StringToInt(str1);
int id2 = StringToInt(str2);
Graph[id1][id2] += time;
Graph[id2][id1] += time;
weight[id1] += time;
weight[id2] += time;
}
// for( int i=1;i<numPerson;++i )
// cout<<weight[i]<<" ";
// cout<<endl;
// memset(visit,0,sizeof(visit));
int count = 0;
map<string,int> gangs;
for( int i=1;i<numPerson;++i ) //节点编号从1开始.
{
if( visit[i] == 0 )
{
int members = 0,maxWeight = 0,totalWeight = 0;
head = 0;
DFS(i,members,maxWeight,totalWeight);
if( members > 2 && totalWeight/2 > k )
{
gangs[intToString[head]] = members; //存储满足条件团伙信息
count++; //团伙个数
}
// cout<<intToString[head]<<" "<<members<<" "<<totalWeight/2<<endl;
}
}
cout<<count<<endl;
map<string,int>::iterator it; // 对map进行遍历,map<type1,type2>会自动按照type1进行排序
for( it = gangs.begin();it != gangs.end();++it)
{
cout<<it->first<<" "<<it->second<<endl;
}
return 0;
}
1034. Head of a Gang (30)
最新推荐文章于 2020-08-21 00:07:48 发布