PAT1034. Head of a Gang

#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <set>
#include <functional>
#include <string>
#include <queue>
using namespace std;

int N;
int K;
vector<string> names;
int totalTime[2005];
int road[2005][2005];
bool isReached[2005];


class Res
{
public:
	int head;
	int count;
};
vector<Res> results;
void bfs(int start)
{
	queue<int> Q;
	vector<int> res;
	res.push_back(start);
	Q.push(start);
	isReached[start] = true;

	int sum = 0;
	while(Q.size()>0)
	{
		int cur = Q.front();
		Q.pop();

		for(int i=0;i<names.size();i++)
		{
			int rd = road[cur][i];
			if(rd>0)
			{
				sum += rd;
				road[cur][i]=0;
				road[i][cur]=0;
				if(!isReached[i])
				{
					Q.push(i);
					res.push_back(i);
					isReached[i] = true;
				}
			}

		}

	}
	if(sum>K && res.size()>2)
	{
		Res re;
		re.count = res.size();
		int head = res[(max_element(res.begin(),res.end(),[=](int a,int b){return totalTime[a]<totalTime[b];})-res.begin())];
		re.head = head;
		results.push_back(re);
	}
}
bool comp(const Res& a, const Res& b)
{
	return names[a.head]<names[b.head]; 
}
int main()
{
	scanf("%d %d",&N,&K);

	for(int i=0;i<N;i++)
	{
		char tmpna[5],tmpnb[5];
		int time;
		scanf("%s %s %d",tmpna,tmpnb,&time);

		string na(tmpna),nb(tmpnb);
		int ida,idb;

		vector<string>::iterator posa = find(names.begin(),names.end(),na);
		if(posa == names.end())
		{
			names.push_back(na);
			ida = names.size()-1;
		}else
			ida = posa-names.begin();

		vector<string>::iterator posb = find(names.begin(),names.end(),nb);
		if(posb == names.end())
		{
			names.push_back(nb);
			idb = names.size()-1;
		}else
			idb = posb-names.begin();
		road[ida][idb] += time;
		road[idb][ida] += time;
		totalTime[ida] += time;
		totalTime[idb] += time;
	}

	for(int i=0;i<names.size();i++)
	{
		if(!isReached[i])
		{
			bfs(i);
		}
	}
	sort(results.begin(),results.end(),comp);
	printf("%d\n",results.size());
	for(int i=0;i<results.size();i++)
	{
		printf("%s %d\n",names[results[i].head].c_str(),results[i].count);
	}
	return 0;
}



你可能感兴趣的:(PAT1034. Head of a Gang)