【并查集】 HDOJ 4313 Matrix
2015-02-11 13:39
155 查看
就是求最大生成森林!按权值把边从大到小排序,然后用并查集做就可以了。。。
#include <iostream> #include <queue> #include <stack> #include <map> #include <set> #include <bitset> #include <cstdio> #include <algorithm> #include <cstring> #include <climits> #include <cstdlib> #include <cmath> #include <time.h> #define maxn 100005 #define maxm 100005 #define eps 1e-7 #define mod 1000000007 #define INF 0x3f3f3f3f #define PI (acos(-1.0)) #define lowbit(x) (x&(-x)) #define mp make_pair #define ls o<<1 #define rs o<<1 | 1 #define lson o<<1, L, mid #define rson o<<1 | 1, mid+1, R #define pii pair<int, int> #pragma comment(linker, "/STACK:16777216") typedef long long LL; typedef unsigned long long ULL; //typedef int LL; using namespace std; LL qpow(LL a, LL b){LL res=1,base=a;while(b){if(b%2)res=res*base;base=base*base;b/=2;}return res;} LL powmod(LL a, LL b){LL res=1,base=a;while(b){if(b%2)res=res*base%mod;base=base*base%mod;b/=2;}return res;} // head struct node { int a, b, w; }e[maxm]; int f[maxn]; bool flag[maxn]; int n, m; LL ans; int find(int x) { return x == f[x] ? f[x] : find(f[x]); } bool merge(int a, int b) { int aa = find(a), bb = find(b); if(aa != bb && !(flag[aa] & flag[bb])) { f[aa] = f[bb]; flag[bb] |= flag[aa]; return true; } else return false; } int cmp(node a, node b) { return a.w > b.w; } void read() { scanf("%d%d", &n, &m); int t; ans = 0; for(int i = 0; i <= n; i++) f[i] = i; memset(flag, 0, sizeof flag); for(int i = 1; i < n; i++) scanf("%d%d%d", &e[i].a, &e[i].b, &e[i].w), ans += e[i].w; for(int i = 1; i <= m; i++) { scanf("%d", &t); flag[t] = true; } } void work() { sort(e+1, e+n, cmp); for(int i = 1; i < n; i++) if(merge(e[i].a, e[i].b)) ans -= e[i].w; printf("%I64d\n", ans); } int main() { int _; while(scanf("%d", &_)!=EOF) { while(_--) { read(); work(); } } return 0; }
相关文章推荐
- hdu 4313 - Matrix(最小生成树,并查集)
- HDU 4313 Matrix(并查集/破坏边使得k个点两两不连通的最少代价)
- HDU 4313 Matrix (贪心+并查集)
- HDOJ 题目4313 Matrix(类似克鲁斯卡尔)
- HDU 4313 Matrix(贪心+并查集)
- HDU 4313 Matrix(并查集)
- 并查集--HDU - 4313 Matrix
- Kruskal HDOJ 4313 Matrix
- HDU 4313 Matrix(并查集|最小生成树变种)
- hdu 4313 Matrix(并查集)
- hdu 4313 Matrix 并查集 多校联合赛(二) 第四题
- HDU 4313 Matrix (贪心+并查集)
- 并查集(union-find set)hdoj/hdu 1232畅通工程
- 并查集练习3:HDOJ4496 WA
- Educational Codeforces Round 31 E. Binary Matrix 并查集
- 【HDOJ 5652】 India and China Origins(并查集)
- HDOJ 3047 带权并查集
- 【网络流】 HDOJ 4307 Matrix
- 【hdoj5671】Matrix
- hdoj 5015 233 Matrix