您的位置:首页 > 其它

HDU-3038 How Many Answers Are Wrong

2014-01-19 12:08 363 查看
题目链接

#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
#define maxn 200020

int n,m;
int p[maxn],weight[maxn];     //并查集祖先结点 并查集权值

int find(int x)
{
if( p[x] == x ) return x;
int t = p[x];
p[x] = find( p[x] );
weight[x] += weight[t];
return p[x];
}

void merge( int x,int y,int a,int b,int v )
{
if( x > y )
{
p[y] = x;
weight[y] = weight[a]-v-weight[b];
}
else
{
p[x] = y;
weight[x] = v + weight[b] - weight[a];
}
}

void init()
{
memset( weight,0,sizeof(weight) );
for( int i = 0; i <= n; i++ )
p[i] = i;
}

int main()
{
//freopen( "data.in","r",stdin );
while(scanf("%d%d",&n,&m) != EOF)
{
init();
int a,b,v,re = 0;
for(int i = 0;i < m;i++)
{
scanf("%d%d%d",&a,&b,&v);
a--;

int x = find(a);
int y = find(b);
if(x == y && weight[a] != weight[b] + v)
{
re++;
}
else if(x != y)
merge(x,y,a,b,v);
}
printf("%d\n",re);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: