您的位置:首页 > 其它

【并查集】 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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: