记一次pat练习:1034 Head of a Gang

题目地址:
https://pintia.cn/problem-sets/994805342720868352/problems/994805456881434624

解法:用深度优先搜索(用栈)计算无向图的联通分量;
学到的知识:
1、map的灵活应用
2、map和vector的遍历

#include<iostream>
#include<map>
#include<vector>
#include<stack>

using namespace std;

int main(){
	
	map<string,vector<string> > m;
	map<string,int> mweight;
	map<string,int> visted;
	stack<string> ms;
	
	map<string,int> ansmap;
	
	int N,K;
	cin >> N >>K;
	string temp1,temp2;
	int weight;
	for(int i=0;i<N;i++){
		cin>>temp1>>temp2>>weight;
		visted[temp1]=0;
		visted[temp2]=0;
		mweight[temp1]+=weight;
		mweight[temp2]+=weight;
		m[temp1].push_back(temp2);
		m[temp2].push_back(temp1);
	}
	
	map<string,vector<string> >::iterator mapiter=m.begin();
	
	string max;
	int count=0;
	int sum=0;
	for(;mapiter!=m.end();mapiter++){
		if(!visted[mapiter->first]){
			count=0;
			sum=0;
			max=mapiter->first;
			
			visted[mapiter->first]=1;
			ms.push(mapiter->first);
			while(!ms.empty()){
				
				string tempstr=ms.top();
				ms.pop();
				
				if(mweight[tempstr]>mweight[max]) max=tempstr;
				count++; 
				sum+=mweight[tempstr];
				
				vector<string>::iterator iter=m[tempstr].begin();
				for(;iter!=m[tempstr].end();iter++){
					if(!visted[*iter]){
						visted[*iter]=1;
					    ms.push(*iter);
					}
				}
	
			}
			
			if(sum/2>K&& count>2) {
				ansmap[max]=count;
			}
			
		}
	}
	
	cout << ansmap.size()<<endl;
	map<string,int>::iterator miter=ansmap.begin();
	for(;miter!=ansmap.end();miter++){
		cout << miter->first<<" "<<miter->second<<endl;
	}
	 
   
} 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值