当前位置: 代码迷 >> 综合 >> HDU 6187 Destroy Walls (最大生成树)
  详细解决方案

HDU 6187 Destroy Walls (最大生成树)

热度:6   发布时间:2024-02-08 04:04:27.0

题意:领土被分割成 n 个地方,国王想到达他领土的每一个地方,现在有一些城墙隔绝了每个地方,拆掉城墙需要耗费一些物力,国王想拆最小的城墙数,花费最小的物力。

题解:最大生成树
要能到达每一个地方,就是不存在环,生成树能满足条件。

花费最少的钱,剩下的就是最多,边权从大到小排序,求一下最大生成树即可。

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<algorithm>
#include<queue>
#include<stack>
#include<cmath>
#include<vector>
#include<fstream>
#include<set>
#include<map>
#include<sstream>
#include<iomanip>
#define ll long long
using namespace std;
const int maxn = 1e5 + 5;
const int inf = 0x3f3f3f3f;
int x, y, f[maxn], u, v, w, m, n;
struct node {int u, v, w;bool operator<(const node& x)const {return w > x.w;}
}edge[maxn << 1];
int Find(int x) {return x == f[x] ? x : f[x] = Find(f[x]);
}
int main() {while (~scanf("%d%d", &n, &m)) {for (int i = 1; i <= n; i++) scanf("%d%d", &x, &y), f[i] = i;int sum = 0;for (int i = 1; i <= m; i++) {scanf("%d%d%d", &u, &v, &w);edge[i] = { u, v, w };sum += w;}sort(edge + 1, edge + m + 1);int temp = 0, temp2 = 0;for (int i = 1; i <= m; i++) {u = edge[i].u;v = edge[i].v;int pa = Find(u);int pb = Find(v);if (pa == pb) continue;f[pa] = pb;++temp;temp2 += edge[i].w;}printf("%d %d\n", m - temp, sum - temp2);}return 0;
}
  相关解决方案