很簡單的題,找出各個節點與根節點的關係,並與輸入的權值進行比較
#include<iostream>
using namespace std;
#define MAX 200005
struct num
{
int father;
int relationship;
}num[MAX];
void make_set(int N)
{
for(int i=0;i<=N;i++)
{
num[i].father=i;
num[i].relationship=0;
}
}
int find_set(int x)
{
if(x==num[x].father)
return x;
int temp=num[x].father;
num[x].father=find_set(num[x].father);
num[x].relationship=num[x].relationship+num[temp].relationship;
return num[x].father;
}
void union_set(int fx,int fy,int a,int b,int weight)
{
num[fy].father=fx;
num[fy].relationship=num[a].relationship-num[b].relationship+weight;
}
void main()
{
int N,K;
int ans,weight,fx,fy,a,b;
while(cin>>N>>K)
{
make_set(N);
ans=0;
while(K-- && cin>>a>>b>>weight)
{
a--;//半開區間內找關係,注意a--
fx=find_set(a);
fy=find_set(b);
if(fx!=fy)
{
union_set(fx,fy,a,b,weight);
}
else
{
if(abs(num[a].relationship-num[b].relationship)!=weight)
ans++;
}
}
cout<<ans<<endl;
}
}