1034 Head of a Gang (30)

//带点权边权的图的遍历
//code:
#include <cstdio>
#include <map>
#include <string>
#include <cstring>
#include <iostream>
using namespace std;
const int MAXN = 2010;
const int INF = 1000000000;
int N, K, numPerson = 0;
map<string, int> stringToInt;  //姓名->编号
map<int, string> intToString;  //编号->姓名
map<string, int> Gang;
int G[MAXN][MAXN], weight[MAXN];
bool vis[MAXN] = {false};
int head, numMember, totalValue;  //全局
int change(string str) {
	if(stringToInt.find(str) != stringToInt.end()) return stringToInt[str];
	else {
		stringToInt[str] = numPerson;
		intToString[numPerson] = str;
		return numPerson ++;
	}
}
void dfs(int i) {
	if(vis[i] == false) {
		vis[i] = true;
		numMember ++;
		if(weight[i] > weight[head]) head = i;
		for(int j=0; j<numPerson; j++) {
			if(G[i][j] > 0) {
				totalValue += G[i][j];
				G[i][j] = G[j][i] = 0;  标记边的方式,即用完就去掉
				dfs(j);
			}
		}
	}
}
void dfsTrave() {
	for(int i=0; i<numPerson; i++) {
		if(vis[i] == false) {
			head = i;  //i
			numMember = 0;
			totalValue = 0;  
			dfs(i);
			if(numMember > 2 && totalValue > K) Gang[intToString[head]] = numMember;
		}
	}
}
int main() {
	scanf("%d%d",&N,&K);
	string str1, str2;
	int id1, id2, w;
	for(int i=0; i<N; i++) {
		cin >> str1 >> str2 >> w;
		id1 = change(str1);
		id2 = change(str2);
		weight[id1] += w;  //与w有联系的都是增加w
		weight[id2] += w;  //与w有联系的都是增加w
		G[id1][id2] += w;  //d1->id2的边权增加w
		G[id2][id1] += w;  //id2->id1的边权增加w
	}
	memset(vis,false,sizeof(vis));
	dfsTrave();
	printf("%d\n",Gang.size());
	for(map<string, int>::iterator it = Gang.begin(); it != Gang.end(); it++)
		cout << it->first << " " << it->second << endl;  //错误:printf("%s %d\n",it->first,it->second);
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值