使用并查集解决head of gang

1034 Head of a Gang (30 分)

 

#include<iostream>
#include<map>
#include<string>
#include<vector>
using namespace std;

const int maxn=2010;  //设置最大值 
int num=0;int n,k;
int weight[maxn]; //每个gang的通话次数 
vector<int> v[maxn]; 
map<string,int> stringToInt;
map<int,string> intToString;
map<string,int> gang;


struct people{
	int w;
	int father;
}peo[2010];


//将人名转化为数字编号 
int change(string s){ 
	if(stringToInt.find(s)!=stringToInt.end()){
		return stringToInt[s];
	}
	else{
		stringToInt[s]=num;
		intToString[num]=s;
		peo[num].father=num;
		return num++;
	}
}

//寻找根节点 
int findFather(int x){
	int a=x;
	while(x!=peo[x].father){
		x=peo[x].father; 
	}
	int max=x;  //寻找连通分量中的最大结点 
	while(a!=peo[a].father){   //压缩路径 
		int z=a;
		if(peo[z].w>peo[max].w){
			max=z;
		}
		a=peo[x].father;
		peo[z].father=x;
	}
	if(max!=x){     //最大结点不是根节点则交换 
		peo[max].father=max;
		peo[x].father=max;
	}
	return max;
}

//合并结点 
void Union(int a,int b){
	int A=findFather(a);
	int B=findFather(b);
	if(A!=B){
		if(peo[A].w<=peo[B].w)  
			peo[A].father=B;
		else 
			peo[B].father=A;
	}
}

//输入结点初始化 
void init(){
	int i;
	string s1,s2;
	int w;
	for(i=1;i<=n;i++){
		cin>>s1>>s2>>w;
		int id1=change(s1);
		int id2=change(s2);
		peo[id1].w+=w;
		peo[id2].w+=w;
		v[id1].push_back(w);  //用向量保存边权 
		Union(id1,id2);
	}
}

//遍历 
void travel(){
	int i,id,w;
	for(i=0;i<num;i++){
		id=findFather(i);
		if(!v[i].empty()){
			for(int j=0;j<v[i].size();j++){
				weight[id]+=v[i][j];
			}
		}
		gang[intToString[id]]+=1;
	}
	map<string,int>::iterator it;
	for(it=gang.begin();it!=gang.end();it++){
		string s=it->first;
		id=stringToInt[s];
		if(weight[id]<=k){
			gang.erase(it);
			continue;
		}
		if(it->second<3){
			gang.erase(it);
		}	
	}
}

int main(){
	cin>>n>>k;
	init();
	travel();
	map<string,int>::iterator it;
	cout<<gang.size()<<endl;
	for(it=gang.begin();it!=gang.end();it++){
		cout<<it->first<<" "<<it->second<<endl;
	}
	return 0;
} 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值