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

题目链接

食物链类似的题,主要是在于转化,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[];
int rank[];
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 = ;i <= n;i ++)
{
o[i] = i;
rank[i] = ;
}
ans = ;
for(i = ;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 ;
}
上一篇:Python保护变量、私有变量、私有方法


下一篇:windows下openssl编译