1034 Head of a Gang

25 篇文章 0 订阅
6 篇文章 0 订阅

 

 这道题是DFS题,邻接矩阵存储,并且在每个联通图中找出total>K的联通图,

并记录此联通图中顶点权值最大的顶点,即head of hang

这里用map存储每个用户的名称及映射顶点序号.

输出的时候,也是用map<string, int> Gang

最后输出Gang.size(),以及依次输出 Gang->first\Gang.second

有个case过不了段错误是因为,给的数据信息是1000条,意味着可能有2000个用户,所以maxn取2010


#include <cstdio>
#include <iostream>
#include <string>
#include <map>
#include <set>
#include <cstring>
#include <vector>
#include <sstream>
#include <algorithm>
#include <cmath>
#include <ctype.h>
using namespace std;
const int maxn = 2010;
const int INF = 1000000000;
map<int, string> intTostring;//编号->人数
map<string, int> stringToint;//姓名->编号
map<string, int> Gang;//head->人数
int G[maxn][maxn] = { 0 }, weight[maxn] = { 0 };
int n, k, numperson = 0;
int vis[maxn] = { 0 };//标记访问
void DFS(int nowvisit, int &head, int &numMember, int &totalvalue) {
	numMember++;
	vis[nowvisit] = 1;
	if (weight[nowvisit] > weight[head]) {
		head = nowvisit;//head只是记录点权最大的结点,遍历主要还是边为主
	}
	for (int i = 0; i < numperson; i++) {
		if (G[nowvisit][i] > 0) {
			totalvalue += G[nowvisit][i];
			G[nowvisit][i] = G[i][nowvisit] = 0;
			if (vis[i] == 0) {
				DFS(i, head, numMember, totalvalue);
			}
		}
	}
}
void DFSTrave() {
	for (int i = 0; i < numperson; i++) {//未必是联通图,所有邻接矩阵 O(n^2)
		if (vis[i] == 0) {
			int head = i, numMember = 0, totalvalue = 0;//头目,成员数,总边权
			DFS(i, head, numMember, totalvalue);//一次dfs一个联通图
			if (numMember > 2 && totalvalue > k) {
				Gang[intTostring[head]] = numMember;//此联通图的head
			}
		}
	}
}
int change(string str) {
	if (stringToint.find(str) != stringToint.end()) {
		return stringToint[str];
	}
	else {
		stringToint[str] = numperson;
		intTostring[numperson] = str;//第几个人
		return numperson++;
	}
}
int main() {
	int w;
	string str1, str2;
	cin >> n >> k;
	for (int i = 0; i < n; i++) {
		cin >> str1 >> str2 >> w;
		int id1 = change(str1);
		int id2 = change(str2);//记录名字的编号
		weight[id1] += w;//结点权值
		weight[id2] += w;
		G[id1][id2] += w;//边权值加w
		G[id2][id1] += w;
	}
	//各边权值构造完毕
	DFSTrave();
	cout << Gang.size() << endl;
	for (auto it = Gang.begin(); it != Gang.end(); it++) {
		cout << it->first << " " << it->second << endl;
	}
	return 0;
}

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值