1034. Head of a Gang (30)-PAT甲级真题

在这里插入图片描述

#include<iostream>
#include<string>
#include<map>
using namespace std;
const int MAX = 2005;
map<string, int> nametoid;
map<int, string> idtoname;
map<string, int> gang;
int pointw[MAX]; //点权
int G[MAX][MAX]; //邻接矩阵
int n,k,num;
bool vis[MAX] = { false }; //是否被访问
int change(string a) {  //将name转换为id
	if (nametoid.find(a) != nametoid.end()) {
		return nametoid[a];
	}
	else {
		nametoid[a] = num;
		idtoname[num] = a;
		return num++; //num为总人数,但这里返回的是id,同时num++
	}
}
void dfs(int id,int &head,int &tnum,int &w) {   
//传引用是为了每次递归计算的结果都保存在初始的变量中,因为这个head、tnum、w是整个gang的
	vis[id] = true;
	tnum++; //total number of members of the gang
	if (pointw[id] > pointw[head]) head = id;
	for (int u = 0; u < num; u++) {
		if (G[id][u] > 0) {
			w += G[id][u];  //总权值
			G[id][u] = G[u][id] = 0; //删除,防止回头
			if (vis[u] == false) dfs(u, head, tnum, w);
		}
	}
}
void trave() {  //遍历图
	for (int i = 0; i < num; i++) {
		if (vis[i] == false) {
			int head = i, tnum = 0, w = 0;
			dfs(i, head, tnum, w);
			if (tnum > 2 && w > k) {
				gang[idtoname[i]] = tnum;
			}
		}
	}
}
int main() {
	cin >> n >> k;
	while (n--) {
		string a, b;
		cin >> a >> b;
		int w; cin >> w;
		int ida = change(a);
		int idb = change(b);
		pointw[ida] += w;
		pointw[idb] += w;
		G[ida][idb] += w;
		G[idb][ida] += w;
	}
	trave();
	cout << gang.size() << endl;
	for (auto it=gang.begin(); it != gang.end(); it++) {
		cout << it->first << " " << it->second << endl;
	}
	return 0;
}
发布了26 篇原创文章 · 获赞 5 · 访问量 442

猜你喜欢

转载自blog.csdn.net/weixin_43590232/article/details/104038866