PAT A 1034 Head of a Gang (30 分)

一、思路

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

二、代码

#include <iostream>
#include <map>
#include <string>
#include <vector>
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;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值