A1034 Head of a Gang [图的dfs遍历]

在这里插入图片描述

#include<iostream>
#include<vector>
#include<queue>
#include<stack>
#include<string>
#include<math.h>
#include<algorithm>
#include<map>
using namespace std;
int weight[2001], G[2001][2001];
bool visit[2001];
map<int, string>inttoString;
map<string, int>stringtoInt;
map<string, int>gang;
int allnumber = 0, k;

void dfs(int nowi, int& number,int& total,int& head)
{
	number++;
	visit[nowi] = true;
	if (weight[nowi] > weight[head])
	{
		head = nowi;
	}
	for (int i = 0; i < allnumber; i++)
	{
		if (G[nowi][i] > 0)
		{
			total += G[nowi][i];
			G[nowi][i] = G[i][nowi] = 0;
			if (visit[i] == false)
			{
				dfs(i, number, total, head);
			}
		}
	}
}

void dfstu()
{
	for (int i = 0; i < allnumber; i++)
	{
		if (visit[i] == false)
		{
			int head = i, number = 0, total = 0;
			dfs(i, number, total, head);
			if (number > 2 && total > k)
			{
				gang[inttoString[head]] = number;
			}
		}
	}
}

int change(string str)
{
	if (stringtoInt.find(str) != stringtoInt.end())
	{
		return stringtoInt[str];
	}
	else
	{
		stringtoInt[str] = allnumber;
		inttoString[allnumber] = str;
		return allnumber++;
	}
}



int main()
{
	int w;
	string str1, str2;
	int n,m;
	cin >> n >> k;
	for (int i = 0; i < n; i++)
	{
		cin >> str1 >> str2 >> m;
		int id1 = change(str1);
		int id2 = change(str2);
		weight[id1] += m;
		weight[id2] += m;
		G[id1][id2] += m;
		G[id2][id1] += m;
	}
	dfstu();
	cout << gang.size() << endl;
	for (auto it = gang.begin(); it != gang.end(); it++)
	{
		cout << it->first << " " << it->second << endl;
	}
	return 0;

}
posted @ 2020-07-29 08:35  _Hsiung  阅读(48)  评论(0编辑  收藏  举报