分析 :DFS的实现,本题与普通DFS关键的不同就是用字符串来对应数据,使用map即可,代码二内存超限了,无语
代码一:AC
#include <iostream>
#include <cstring>
#include <vector>
#include <stdio.h>
#include <queue>
#include <math.h>
#include <stack>
#include <algorithm>
#include <map>
#include <set>
#define MAX 99999999
typedef long long ll;
using namespace std;
int n, k;
map< string, int > weight;
map< string, map< string, int >> road;
map< string, int > visi;
map< string, vector< string>> people;
set< string> man;
map< string, int > ans;
int cnt;
int relation;
string head;
void dfs ( string root)
{
cnt++ ;
relation + = weight[ root] ;
visi[ root] = 1 ;
if ( weight[ root] > weight[ head] )
head = root;
for ( int i = 0 ; i< people[ root] . size ( ) ; i++ )
if ( ! visi[ people[ root] [ i] ] )
dfs ( people[ root] [ i] ) ;
}
int main ( )
{
cin>> n>> k;
for ( int i = 0 ; i< n; i++ )
{
string s1, s2;
int x;
cin>> s1>> s2>> x;
man. insert ( s1) ;
man. insert ( s2) ;
people[ s1] . push_back ( s2) ;
people[ s2] . push_back ( s1) ;
weight[ s1] + = x;
weight[ s2] + = x;
road[ s1] [ s2] + = x;
}
int gang = 0 ;
for ( auto it = man. begin ( ) ; it!= man. end ( ) ; it++ )
{
cnt = 0 ;
relation = 0 ;
if ( ! visi[ * it] ) {
head = * it;
dfs ( * it) ;
if ( cnt > 2 && relation/ 2 > k)
{
gang ++ ;
ans[ head] = cnt;
}
}
}
cout<< gang<< endl;
for ( auto it = ans. begin ( ) ; it!= ans. end ( ) ; it++ )
cout<< it- > first<< " " << it- > second<< endl;
return 0 ;
}
代码二
#include <iostream>
#include <cstring>
#include <vector>
#include <stdio.h>
#include <queue>
#include <math.h>
#include <stack>
#include <algorithm>
#include <map>
#include <set>
#define MAX 99999999
typedef long long ll;
using namespace std;
int n, k;
map< string, int > weight;
map< string, map< string, int >> road;
map< string, int > visi;
map< string, map< string, int >> visi2;
set< string> man;
map< string, int > ans;
int cnt;
int relation;
string head;
void dfs ( string root)
{
if ( ! visi[ root] )
cnt++ ;
visi[ root] = 1 ;
if ( weight[ root] > weight[ head] )
head = root;
for ( auto it = man. begin ( ) ; it!= man. end ( ) ; it++ )
{
if ( ! visi2[ root] [ * it] && road[ root] [ * it] != 0 )
{
visi2[ root] [ * it] = 1 ;
relation + = road[ root] [ * it] ;
dfs ( * it) ;
}
}
}
int main ( )
{
cin>> n>> k;
for ( int i = 0 ; i< n; i++ )
{
string s1, s2;
int x;
cin>> s1>> s2>> x;
man. insert ( s1) ;
man. insert ( s2) ;
road[ s1] [ s2] + = x;
weight[ s1] + = x;
weight[ s2] + = x;
}
int gang = 0 ;
for ( auto it = man. begin ( ) ; it!= man. end ( ) ; it++ )
{
cnt = 0 ;
relation = 0 ;
if ( ! visi[ * it] ) {
head = * it;
dfs ( * it) ;
if ( cnt > 2 && relation > k)
{
gang ++ ;
ans[ head] = cnt;
}
}
}
cout<< gang<< endl;
for ( auto it = ans. begin ( ) ; it!= ans. end ( ) ; it++ )
cout<< it- > first<< " " << it- > second<< endl;
return 0 ;
}