您的位置:首页 > 其它

HDU 3038 how many answers are wrong(带权并查集)

2014-03-24 04:39 411 查看
很简单的题,找出各个节点与根节点的关系,并与输入的权值进行比较

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

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: