Ideas:
-
Weighted disjoint-set, interval statistics .
-
Weighted disjoint-set and common disjoint-set difference:
- Find function can not be written recursively, and to be able to dynamically update all points on the path to Val .
- UNION function to change Val [Parr] , you need not change their Val [R & lt] .
-
This 题 Note:
- Title did not say a multi-set of use cases, you also have to read the end of the file, otherwise it will WA .
- Interval statistics need to become left and right to open and close (so for: 6,6,1 class restriction will not wrong).
Code:
- 46ms 2972kB
//46ms 2972kB
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int maxn = 200005;
int N,M;
int ans;
int par[maxn];
int val[maxn];//value后缀和
void INIT(){
memset(par , -1 , sizeof(par));
memset(val , 0 , sizeof(val));
ans = 0;
return ;
}
int FIND(int i){
if(par[i] == -1)
return i;
int temp = par[i];
par[i] = FIND(par[i]);
val[i] += val[temp];
return par[i];
}
int main(){
while(cin>>N>>M){
INIT();
while(M--){
int l , r , w;
scanf("%d%d%d" , &l , &r , &w);
int parl = FIND(l-1) ;
int parr = FIND(r) ;
if(parr == parl)
if(val[l-1] + w != val[r])
ans++;
else ;
else{
par[parr] = parl;
val[parr] = val[l-1] + w - val[r] ;
//为什么不需要改 val[r] : par[r]依然是parr , 且parr和 r之间的势差仍为val[r]
}
}
printf("%d\n" , ans);
}
return 0;
}