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;
}