您的位置:首页 > 其它

杭电hdu 3038 how many answers are wrong 并查集求解

2012-03-23 10:57 337 查看
http://acm.hdu.edu.cn/showproblem.php?pid=3038

经过网上的搜罗,基本上明白了这个题的意思,网站http://hi.baidu.com/fp_lv/blog/item/a471530a86df7b90d53f7c2c.html讲解的很清楚,我这里只记录下网址和我的代码,以便以后随时查看。

#include <stdio.h>
#define MAX 200001

int father[MAX];
int sum[MAX];//存储从1到i相加的结果

int n,m;
int ai, bi, si;

void init()
{
for(int i = 0; i <= n; i ++){
father[i] = i;
sum[i] = 0;
}
}

int getfather(int x)
{
if(x == father[x])
return x;
int now = getfather(father[x]);//
sum[x] += sum[father[x]];//需要我研究的地方
father[x] = now;
return now;
}

bool join(int a, int b)
{
int fa = getfather(a);
int fb = getfather(b);
if(fa == fb)return false;
father[fb] = fa;
sum[fb] = sum[a] - sum[b] + si;//
return true;
}

int main()
{
//	freopen("input.txt","r",stdin);
//	freopen("output.txt","w",stdout);

while(~scanf("%d%d",&n,&m)){
init();
int ans = 0;
while(m--){
scanf("%d%d%d",&ai, &bi, &si);
ai --;
if(!join(ai, bi)&&sum[bi] - sum[ai] != si)ans ++;
}
printf("%d\n", ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: