您的位置:首页 > 其它

HDU 3038 How Many Answers Are Wrong(种类并查集)

2014-05-05 07:59 405 查看
题目链接

食物链类似的题,主要是在于转化,a-b的和为s,转换为b比a-1大s。然后并查集存 此节点到根的差。

假如x的根为a,y的根为b:

b - y = rank[y]

a - x = rank[x]

y - x = s

可以推出b - a = rank[y] - rank[x] + s;

并查集 延迟更新什么的,都忘了啊。

还有这题,如果是x--的话,记得更新0的根。

#include <cstring>
#include <cstdio>
#include <string>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
using namespace std;
int o[200001];
int rank[200001];
int find(int x)
{
if(x == o[x]) return x;
int t = find(o[x]);
rank[x] = rank[o[x]] + rank[x];
return o[x] = t;
}
int main()
{
int n,m,i,a,b,s,ans,x,y;
while(scanf("%d%d",&n,&m)!=EOF)
{
for(i = 0;i <= n;i ++)
{
o[i] = i;
rank[i] = 0;
}
ans = 0;
for(i = 0;i < m;i ++)
{
scanf("%d%d%d",&x,&y,&s);
x -- ;
a = find(x);
b = find(y);
if(a != b)
{
o[a] = b;
rank[a] = rank[y] - rank[x] + s;
}
else
{
if(rank[x] != rank[y] + s)
ans ++;
}
}
printf("%d\n",ans);
}
return 0;
}


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