您的位置:首页 > 其它

HDU 3038 带权并查集

2017-08-02 16:04 148 查看


可以清晰看出val - dist[y] + dist[x] 就是yy到祖先的距离dist[yy]

#include <iostream>
#include <cstdio>
#include <string.h>
using namespace std;
const int AX = 2e5+666;
const int MAXN = 4e4+666;
int pre[AX];
int dist[AX];
int ans ;
int n,m;

void init(){
for( int i = 1 ; i <= n ; i++ ){
pre[i] = i;
dist[i] = 0;
}
}

int find(int x){
if( x!= pre[x] ){
int t = pre[x];
pre[x] = find(pre[x]);
dist[x] += dist[t]; //压缩路径时多出的更新操作
}
return pre[x];
}

void mix(int x,int y,int val){
int xx = find(x);
int yy = find(y);
if( xx != yy ){
pre[yy] = xx ;
dist[yy] = val - dist[y] + dist[x]; //这一步的理解在开头给出
}else{
if( dist[yy] != val - dist[y] + dist[x] ) ans++;
}
}

int main(){
while(~scanf("%d%d",&n,&m)){
ans = 0;
init();
int x,y,val;
while( m-- ){
scanf("%d%d%d",&x,&y,&val);
mix(x-1,y,val);
}
printf("%d\n",ans);

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