缴纳过路费--并查集+优先队列

利用并查集建立联通块,然后>=l的时候统计城市对的个数,>r退出

https://www.luogu.com.cn/problem/P11005

#include
using namespace std;
#define N 100011
typedef long long ll;
typedef pair PII;
ll n,m,l,r;
ll mod=1000000000+7;
typedef struct edge
{
	int u,v;ll w;
}edge;
struct cmp
{
	bool operator()(const edge &a,const edge &b)const
	{
		return a.w>b.w;
	}
};
priority_queue,cmp> pq;
int fa[N];
ll an[N];
ll ans;
int find(int x)
{
	if(fa[x]==x) return x;
	else return fa[x]=find(fa[x]);
}
int main()
{ 
cin>>n>>m>>l>>r;
for(int i=1;i<=n;i++) fa[i]=i,an[i]=1;///an就是联通块,初始化为1 
for(int i=0;i>u>>v>>w;
	pq.push({u,v,w});
}
int f=0;
while(pq.size())
{
	edge a=pq.top();
	pq.pop();
	if(a.w>r) break;
	int u=a.u;int v=a.v;
	if(find(u)!=find(v))
	{
		if(a.w>=l)ans+=(an[find(u)]*an[find(v)]);///一定是>=l再统计 
		   										 ///前面的对数与ans无关 
		an[find(v)]+=an[find(u)];///维护联通块 
		fa[find(u)]=find(v);
	}
} 
cout<

你可能感兴趣的:(算法)