PAT A.1034 Head of a Gang
PAT A.1034 Head of a Gang
# include <bits/stdc++.h>
using namespace std;
const int maxn= 2010 ;
const int INF= 1000000000 ;
map< int , string> intToString;
map< string, int > stringToInt;
map< string, int > Gang;
int G[ maxn] [ maxn] = { 0 } ;
int weight[ maxn] = { 0 } ;
int n, k, sum= 0 ;
bool vis[ maxn] = { false } ;
void DFS ( int nowVisit, int & head, int & num, int & total)
{
num++ ;
vis[ nowVisit] = true ;
if ( weight[ nowVisit] > weight[ head] )
{
head= nowVisit;
}
for ( int i= 0 ; i< sum; i++ )
{
if ( G[ nowVisit] [ i] > 0 )
{
total+= G[ nowVisit] [ i] ;
G[ nowVisit] [ i] = G[ i] [ nowVisit] = 0 ;
if ( vis[ i] == false )
{
DFS ( i, head, num, total) ;
}
}
}
}
void DFSTrave ( )
{
for ( int i= 0 ; i< n; i++ )
{
if ( vis[ i] == false )
{
int head= i;
int num= 0 ;
int total= 0 ;
DFS ( i, head, num, total) ;
if ( num> 2 && total> k)
{
Gang[ intToString[ head] ] = num;
}
}
}
}
int change ( string str)
{
if ( stringToInt. find ( str) != stringToInt. end ( ) )
return stringToInt[ str] ;
else
{
stringToInt[ str] = sum;
intToString[ sum] = str;
return sum++ ;
}
}
typedef long long LL;
int main ( )
{
int w;
string str1, str2;
cin>> 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;
}
DFSTrave ( ) ;
cout<< Gang. size ( ) << endl;
map< string, int > :: iterator it;
for ( it= Gang. begin ( ) ; it!= Gang. end ( ) ; it++ )
{
cout<< it-> first<< " " << it-> second<< endl;
}
return 0 ;
}