【PAT】A1034Head of a Gang

昨天准备学完图相关的知识,但是学起来挺懵的,理解起来不难,但自己一回想,又什么都想不起来。

翻来覆去看图的遍历,还是觉得有点没到位。

所以做题来检测一下,果然学和自己做是两码事。

先看的书,又看的柳婼的代码。思路一样。

自己照着打了一遍,又自己实现了一遍,总体并不难,关键就是三十分的题,要花多点时间读懂题意。

只发现一个对于我来说的注意事项:

两个人打电话,可能不止打一次。

#include<string>
#include<iostream>
#include<map>
using namespace std;
map<string,int> sti;
map<int,string> its;
int id=1,K;
int G[2010][2010],weight[2010];
bool vis[2010];
int getid(string str){
	if(sti[str]==0){
		sti[str]=id;
		its[id]=str;
		return id++;
	}else
		return sti[str];
}

void DFS(int u,int &head,int &numMember,int &totalweight){
	numMember++;
	vis[u]=true;
	if(weight[u]>weight[head])
		head=u;
	for(int j=1;j<id;j++){
		if(G[j][u]>0){
			totalweight+=G[j][u];
			G[j][u]=G[u][j]=0;
			if(vis[j]==false)
				DFS(j,head,numMember,totalweight);
		}
	}
}
map<string,int> ans;
void DFSTrave(){
	for(int i=1;i<id;i++){
		if(vis[i]==false){
			int head=i,numMember=0,totalweight=0;
			DFS(i,head,numMember,totalweight);
			if(numMember>2&&totalweight>K)
				ans[its[head]]=numMember;
		}
	}
}

int main(){
	int N;
	cin >> N >> K;
	for(int i=0;i<N;i++){
		string str1,str2;
		int temp;
		cin >>str1 >> str2 >>temp;
		int id1=getid(str1);
		int id2=getid(str2);
		weight[id1]+=temp;
		weight[id2]+=temp;
		G[id1][id2]+=temp;//两个人不一定只通一次电话
		G[id2][id1]+=temp;
	}
	DFSTrave();
	cout << ans.size() << endl;
	for(auto it=ans.begin();it!=ans.end();it++)
		cout << it->first << " " << it->second <<endl;
	return 0;
}

原文地址:https://www.cnblogs.com/hebust/p/9870006.html