1034 Head of a Gang(7ms,并查集版,比图的版本快得多,更省内存

 

9ms,并查集版,比图的版本得多,更更更省内存

题目

题意: 给出1000条以内的通话记录A B和权值w,和阈值k,如果一个团伙人数超过2人并且通话总权值超过k,令团伙里面的自身权值的最大值为头目,输出所有满足条件的团伙的头目,和他们团伙里面的人数

tip:并查集 + map映射 + sort

#include<iostream>
#include<vector>
#include<map>
#include<set>
#include<algorithm>
using namespace std;
struct ss {
	int num;//真正的头头编号
	int count=1;//团伙人数
	int time=0;//每个人通话总时间
	int counttime=0;//总时间
};
map<string,int> nametonum;
map<int,string> numtoname;
map<int,struct ss> user;
int father[10003];
void init() {
	for(int i=0; i<10003; ++i)
		father[i]=i;
}
int find(int x) {
	return x==father[x]?father[x]:father[x]=find(father[x]);
}
void Uion(int a,int b) {
	int x=find(a);
	int y=find(b);
	if(x!=y)
		father[x]=y;
}
bool cmp(int a,int b) {
	return numtoname[user[a].num]<numtoname[user[b].num];
}
int main() {
	init();
	int n,m;
	cin>>n>>m;
	set<string> name;
	int c=0;
	for(int i=0; i<n; ++i) {
		string a,b;
		int time;
		cin>>a>>b>>time;
		if(name.find(a)==name.end()) {//登记a姓名
			name.insert(a);
			nametonum[a]=c;
			numtoname[c]=a;
			c++;
		}
		if(name.find(b)==name.end()) {//登记b姓名
			name.insert(b);
			nametonum[b]=c;
			numtoname[c]=b;
			c++;
		}
		user[nametonum[a]].time+=time;
		user[nametonum[b]].time+=time;
		Uion(nametonum[a],nametonum[b]);//建立联系
	}
	vector<int>master;//统计并查集头头 
	for(int i=0; i<n; ++i) {
		if(father[i]==i) {//找出并查集头头
			master.push_back(i);
			user[i].num=i;
		}
	}
	for(int i=0; i<n; ++i) {
		father[i]=find(i);
		//比较头头与其他成员通话时间时长,确定真正输出的头头
		user[father[i]].num=user[user[father[i]].num].time>user[i].time ?user[father[i]].num:i;
		if(father[i]!=i) {//算成员总数
			user[father[i]].count++;
		}
		user[father[i]].counttime+=user[i].time;//算群体内总通话时间
	}
	sort(master.begin(),master.end(),cmp);//对头头输出顺序排序
	vector<int>ans;
	for(int i=0; i<master.size(); ++i)
		if(user[master[i]].counttime>2*m&&user[master[i]].count>2)//gang成立条件
			ans.push_back(master[i]);
	cout<<ans.size()<<endl;//gang数量 
	for(int i=0; i<ans.size(); ++i)
		cout<<numtoname[user[ans[i]].num]<<" "<<user[ans[i]].count<<endl;
	return 0;
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大章鱼(张文哲

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值