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;
}