【HDOJ】3047 Zjnu Stadium

带权并查集。

 /* 3047 */
#include <iostream>
#include <string>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <vector>
#include <deque>
#include <algorithm>
#include <cstdio>
#include <cmath>
#include <ctime>
#include <cstring>
#include <climits>
#include <cctype>
#include <cassert>
#include <functional>
#include <iterator>
#include <iomanip>
using namespace std;
//#pragma comment(linker,"/STACK:102400000,1024000") #define sti set<int>
#define stpii set<pair<int, int> >
#define mpii map<int,int>
#define vi vector<int>
#define pii pair<int,int>
#define vpii vector<pair<int,int> >
#define rep(i, a, n) for (int i=a;i<n;++i)
#define per(i, a, n) for (int i=n-1;i>=a;--i)
#define clr clear
#define pb push_back
#define mp make_pair
#define fir first
#define sec second
#define all(x) (x).begin(),(x).end()
#define SZ(x) ((int)(x).size())
#define lson l, mid, rt<<1
#define rson mid+1, r, rt<<1|1 const int maxn = 5e4+;
int fa[maxn], dis[maxn]; int find(int x) {
if (fa[x] == x)
return x; int tmp = fa[x];
fa[x] = find(fa[x]);
dis[x] += dis[tmp]; return fa[x];
} bool merge(int u, int v, int w) {
int fu = find(u);
int fv = find(v); if (fu == fv) {
if (dis[u]+w!=dis[v])
return false;
return true;
} fa[fv] = fu;
dis[fv] = dis[u] + w - dis[v]; return true;
} int main() {
ios::sync_with_stdio(false);
#ifndef ONLINE_JUDGE
freopen("data.in", "r", stdin);
freopen("data.out", "w", stdout);
#endif int n, m;
int u, v, w;
int ans; while (scanf("%d %d", &n, &m) != EOF) {
rep(i, , n+) {
fa[i] = i;
dis[i] = ;
}
ans = ;
while (m--) {
scanf("%d %d %d", &u, &v, &w);
if (!merge(u, v, w))
++ans;
}
printf("%d\n", ans);
} #ifndef ONLINE_JUDGE
printf("time = %d.\n", (int)clock());
#endif return ;
}
上一篇:lua下的简单OO实现


下一篇:android 自定义命名空间