1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| #include <iostream> #include <string.h> using namespace std; const int maxn = 2e5+10; int pre[maxn]; int dist[maxn];
void init() { memset(dist,0,sizeof dist); for (int i=1; i<maxn; i++) pre[i] = i; } int find(int x) { int temp = pre[x]; if (x == pre[x]) return x; pre[x] = find(pre[x]); dist[x] += dist[temp]; return pre[x]; }
int main() {
int n,m; while (scanf("%d%d",&n,&m) != EOF) { init(); int ans = 0; while (m--) { int a,b,len; scanf("%d%d%d",&a,&b,&len); b++; int ra = find(a); int rb = find(b); if (ra == rb) { if (dist[a] - dist[b] != len) ans++; } else { pre[ra] = rb; dist[ra] = len + dist[b] - dist[a]; } } printf("%d\n",ans); } return 0; }
|