跳到正文

个人记录

P11005 [蓝桥杯 2024 省 Python B] 缴纳过路费

#SUSPENDED#约 2 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 2 分钟

版本

  1. v1当前

错误原因

没有考虑无效边不计入答案。

思路

用并查集维护每一个集合,并用一个数组记录每个集合的大小,可以在连边时累加大小,两个集合的合并的大小就是两个集合的大小之和。

最后,依次按边处理,每次答案累加两个集合的大小的乘积,因为这两个集合中的每个元素都可以互相配对。

代码

C++
#include<bits/stdc++.h>
#define int long long
using namespace std;
int n,m,l,r;
struct edge{
	int u,v,w;
}e[200005];
int fa[100005];
int len[100005];
int find(int x){
	if(fa[x]==x)return x;
	fa[x]=find(fa[x]);
	return fa[x];
}
void mer(int u,int v){
	int x=find(u);
	int y=find(v);
	if(x!=y){
		fa[x]=y;
		len[y]+=len[x];
	}
	return;
}
bool cmp(edge a,edge b){
	return a.w<b.w;
}
int ans;
signed main(){
	ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
	cin>>n>>m>>l>>r;
	for(int i=1;i<=n;i++)fa[i]=i,len[i]=1;
	for(int i=1;i<=m;i++)cin>>e[i].u>>e[i].v>>e[i].w;
	sort(e+1,e+1+m,cmp);
	for(int i=1;i<=m;i++){
		if(e[i].w<l){
			mer(e[i].u,e[i].v);
		}else if(e[i].w<=r){
			int x=find(e[i].u);
			int y=find(e[i].v);
			if(x!=y){
				ans+=len[x]*len[y];
				mer(e[i].u,e[i].v);
			}
		}else break;
	}
	cout<<ans;
	return 0;
}
原文