【HDOJ】3047 Zjnu Stadium

带权并查集。

  1 /* 3047 */
  2 #include <iostream>
  3 #include <string>
  4 #include <map>
  5 #include <queue>
  6 #include <set>
  7 #include <stack>
  8 #include <vector>
  9 #include <deque>
 10 #include <algorithm>
 11 #include <cstdio>
 12 #include <cmath>
 13 #include <ctime>
 14 #include <cstring>
 15 #include <climits>
 16 #include <cctype>
 17 #include <cassert>
 18 #include <functional>
 19 #include <iterator>
 20 #include <iomanip>
 21 using namespace std;
 22 //#pragma comment(linker,"/STACK:102400000,1024000")
 23 
 24 #define sti                set<int>
 25 #define stpii            set<pair<int, int> >
 26 #define mpii            map<int,int>
 27 #define vi                vector<int>
 28 #define pii                pair<int,int>
 29 #define vpii            vector<pair<int,int> >
 30 #define rep(i, a, n)     for (int i=a;i<n;++i)
 31 #define per(i, a, n)     for (int i=n-1;i>=a;--i)
 32 #define clr                clear
 33 #define pb                 push_back
 34 #define mp                 make_pair
 35 #define fir                first
 36 #define sec                second
 37 #define all(x)             (x).begin(),(x).end()
 38 #define SZ(x)             ((int)(x).size())
 39 #define lson            l, mid, rt<<1
 40 #define rson            mid+1, r, rt<<1|1
 41 
 42 const int maxn = 5e4+5;
 43 int fa[maxn], dis[maxn];
 44 
 45 int find(int x) {
 46     if (fa[x] == x)
 47         return x;
 48     
 49     int tmp = fa[x];
 50     fa[x] = find(fa[x]);
 51     dis[x] += dis[tmp];
 52     
 53     return fa[x];
 54 }
 55 
 56 bool merge(int u, int v, int w) {
 57     int fu = find(u);
 58     int fv = find(v);
 59     
 60     if (fu == fv) {
 61         if (dis[u]+w!=dis[v])
 62             return false;
 63         return true;
 64     }
 65     
 66     fa[fv] = fu;
 67     dis[fv] = dis[u] + w - dis[v];
 68 
 69     return true;
 70 }
 71 
 72 int main() {
 73     ios::sync_with_stdio(false);
 74     #ifndef ONLINE_JUDGE
 75         freopen("data.in", "r", stdin);
 76         freopen("data.out", "w", stdout);
 77     #endif
 78     
 79     int n, m;
 80     int u, v, w;
 81     int ans;
 82     
 83     while (scanf("%d %d", &n, &m) != EOF) {
 84         rep(i, 1, n+1) {
 85             fa[i] = i;
 86             dis[i] = 0;
 87         }
 88         ans = 0;
 89         while (m--) {
 90             scanf("%d %d %d", &u, &v, &w);
 91             if (!merge(u, v, w))
 92                 ++ans;
 93         }
 94         printf("%d\n", ans);
 95     }
 96     
 97     #ifndef ONLINE_JUDGE
 98         printf("time = %d.\n", (int)clock());
 99     #endif
100     
101     return 0;
102 }

 

posted on 2015-10-26 11:11  Bombe  阅读(160)  评论(0编辑  收藏  举报

导航