(带权并查集)hihoCoder1515分数调查

hihoCoder1515分数调查

思路:

模板题。权值为子节点比父节点多的分数。

代码:

#include<bits/stdc++.h>
#define pii pair<int,int>
#define ll long long
const int N=1e5+10;
const int mod=1e7+9;
const int maxn=0x3f3f3f3f;
const int minn=0xc0c0c0c0;
const int inf=99999999;
using namespace std;
int fa[N],sum[N]={0};
int find(int x)
{
	if(x!=fa[x])
	{
		int t=fa[x];
		fa[x]=find(fa[x]);
		sum[x]+=sum[t];
	}
	return fa[x];
}
void add(int u,int v,int w)
{
	int t1=find(u),t2=find(v);
	if(t1!=t2)
	{
		fa[t1]=t2;
		sum[t1]=-sum[u]+sum[v]+w;
	}
	return;
}
void ask(int u,int v)
{
	int t1=find(u),t2=find(v);
	if(t1!=t2)
		cout<<-1<<endl;
	else
		cout<<sum[u]-sum[v]<<endl;
	return;
}
int main()
{
	ios::sync_with_stdio(false);
	cin.tie(0);cout.tie(0);
	int n,m,t,i;
	cin>>n>>m>>t;
	for(i=1;i<=n;i++)
		fa[i]=i;
	while(m--)
	{
		int u,v,w;
		cin>>u>>v>>w;
		add(u,v,w);
	}
	while(t--)
	{
		int u,v;
		cin>>u>>v;
		ask(u,v);
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值