PAT A 1034 Head of a Gang (30 分)

一、思路

用map存储无向图,并使用DFS或BFS处理;
遍历进行的工作:
1.统计连通分量数;
2.统计连通分量顶点数;
3.找到连通分量中最大权值顶点;
4.求连通分量中所有边权和(由于无向图每条边会被访问两次,sum_w/2为边权和)

二、代码

#include 
#include 
#include 
#include 
using namespace std;
int cnt, sum, N, K, Max;
map<string, vector<string>> G;
map<string, int> visited, w, ans;
string name1, name2, head;
void dfs( string v )
{
	visited[v] = 1;
	++cnt;
	sum += w[v];
	if( w[v] > w[head] )
		head = v;
	for( int i = 0; i < G[v].size(); ++i )
		if( !visited[G[v][i]] )
			dfs(G[v][i]);
}
int main()
{
	cin >> N >> K;

	for( int i = 0, t; i < N; ++i )
	{
		cin >> name1 >> name2 >> t;
		G[name1].push_back(name2);
		G[name2].push_back(name1);
		w[name1] += t;
		w[name2] += t;
	}
	for( map<string, vector<string>>::iterator it = G.begin(); it != G.end(); ++it )
		if( !visited[it->first] )
		{
			cnt = sum = 0;
			head = it->first;
			dfs(it->first);
			if( cnt > 2 && sum > K * 2 )
				ans[head] = cnt;
		}
	cout << ans.size() << endl;
	for( map<string, int>::iterator it = ans.begin(); it != ans.end(); ++it )
		cout << it->first << " " << it->second << endl;
}

你可能感兴趣的:(PAT,A)