How Many Answers Are Wrong hdu3038

rank[x] 表示从x结点到根节点的值。

首先我们可以把问题稍微转化一下,就是如果已知[3,6],[7,10]俩个区间内各自所有数的和,那么就可以[3,10]内所有数的和,可是,这俩个区间根本就不衔接,所有要稍微处理一下,将左区间值减1,就变成了[2,6],[6,10],这样就方便处理了。

具体注释见代码。

/***********************************************
 * Author: fisty
 * Created Time: 2015/2/27 12:57:32
 * File Name   : D.cpp
 *********************************************** */
#include <iostream>
#include <cstring>
#include <deque>
#include <cmath>
#include <queue>
#include <stack>
#include <list>
#include <map>
#include <set>
#include <string>
#include <vector>
#include <cstdio>
#include <bitset>
#include <algorithm>
using namespace std;
#define Debug(x) cout << #x << " " << x <<endl
#define Memset(x, a) memset(x, a, sizeof(x))
const int INF = 0x3f3f3f3f;
typedef long long LL;
typedef pair<int, int> P;
#define FOR(i, a, b) for(int i = a;i < b; i++)
#define MAX_N 200050
int n, m;
int par[MAX_N], rank[MAX_N];
void init(){
    for(int i = 0;i < MAX_N; i++){
        par[i] = i;
        rank[i] = 0;
    }
}
int find(int x){
    if(x == par[x]) return x;
    int tmp = par[x]; 
    par[x] = find(par[x]);
    //当递归到某一层时,x还未接到根节点上,
    //所以rank[x]表示的是x到par[x]的距离,但par[x]已经接到根节点上了,所以rank[par[x]]表示的是父节点到根节点的距离
    //所以x到根节点的距离就直接等于rank[x]+r[par[x]]
    rank[x] += rank[tmp];

    return par[x];
}
bool unio(int x, int y, int c){
    int fx = find(x);
    int fy = find(y);
    if(fx == fy){
        if(rank[x] + c != rank[y]) return false;
        return true;
    }
    par[fy] = fx;
    //rank[x] 为 x 到 fx的距离
    //rank[y] 为 y 到 fy的距离
    //c 为 y 到 x的距离
    //所以fy到fx的距离为 c + rank[x] - rank[y]
    rank[fy] = rank[x] + c - rank[y] ;        
    return true;
}
int main() {
    //freopen("in.cpp", "r", stdin);
    cin.tie(0);
    ios::sync_with_stdio(false);
    while(cin >> n >> m){
    int cnt = 0;
    init();
    FOR(i, 0, m){
        int u, v, c;
        cin >> u >> v >> c;
        if(!unio(u-1, v, c))
            ++cnt;
    }
    cout << cnt << endl;
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值