(step6.1.8)hdu 3367(Pseudoforest——最小生成树的逆应用)
来源:互联网 发布:姚晨 知乎 编辑:程序博客网 时间:2024/06/10 00:12
题目大意:这也是一刀不需要知道题目什么意思的题。只要能看懂样例就行了
解题思路:类似于最大生成树.
1)最大生成树体现在:
bool compare(const edge& a, const edge& b) {return a.weight > b.weight;}
2)对于两棵树。如果都有环,不可合并。如果有一个环,标记后合并。如果没有环,直接合并。这主要体现在
if (fx != fy) {//两棵树if (visited[fx] && visited[fy]) {//都有环continue;}if (visited[fx] || visited[fy]) {//只有一个有环visited[fx] = visited[fy] = true;}//都没有环sum += e[i].weight;join(fx, fy);} else if (!visited[fx]) {//同一棵树,但是没有环(一棵树可以加一个环)join(fx, fy);visited[fx] = true;sum += e[i].weight;}
代码如下:
/* * 3367_1.cpp * * Created on: 2013年8月27日 * Author: Administrator */#include <iostream>using namespace std;struct edge {int begin;int end;int weight;};const int maxn = 10050;int father[maxn];edge e[maxn * maxn];bool visited[maxn];int find(int x) {if (x == father[x]) {return x;}father[x] = find(father[x]);return father[x];}void join(int x, int y) {int fx = find(x);int fy = find(y);if (fx != fy) {father[fx] = fy;}}int kruscal(int count) {int i;int sum = 0;for (i = 0; i < maxn; ++i) {father[i] = i;}for (i = 0; i < count; ++i) {int fx = find(e[i].begin);int fy = find(e[i].end);if (fx != fy) {//两棵树if (visited[fx] && visited[fy]) {//都有环continue;}if (visited[fx] || visited[fy]) {//只有一个有环visited[fx] = visited[fy] = true;}//都没有环sum += e[i].weight;join(fx, fy);} else if (!visited[fx]) {//同一棵树,但是没有环(一棵树可以加一个环)join(fx, fy);visited[fx] = true;sum += e[i].weight;}}return sum;}bool compare(const edge& a, const edge& b) {return a.weight > b.weight;}int main() {int n, m;while (scanf("%d%d", &n, &m) != EOF, n || m) {memset(father, 0, sizeof(father));memset(visited, 0, sizeof(visited));int i;for (i = 0; i < m; ++i) {scanf("%d%d%d", &e[i].begin, &e[i].end, &e[i].weight);}sort(e, e + m, compare);int sum = kruscal(m);printf("%d\n", sum);}}
- (step6.1.8)hdu 3367(Pseudoforest——最小生成树的逆应用)
- HDU 3367 Pseudoforest 最小生成树
- HDU 3367 Pseudoforest 最小生成树、并查集
- HDU 3367 Pseudoforest (最小生成树,并查集)
- (step6.1.1)hdu 1879(继续畅通工程——最小生成树、kruscal)
- (step6.1.2)hdu 1863(畅通工程——最小生成树)
- (step6.1.3)hdu 1875(畅通工程再续——最小生成树)
- (step6.1.4)hdu 1102(Constructing Roads——最小生成树)
- (step6.1.5)hdu 1233(还是畅通工程——最小生成树)
- (step6.1.6)hdu 1301(Jungle Roads——最小生成树)
- (step6.1.7)hdu 3371(Connect the Cities——最小生成树)
- 3367Pseudoforest 伪森林 最小生成树
- hdu 3367 Pseudoforest(最大生成树)
- HDU 3367 Pseudoforest 最大生成树
- hdu 3367 Pseudoforest 最大生成树
- (step6.3.3)hdu 1150(Machine Schedule——二分图的最小点覆盖数)
- HDU 3367 Pseudoforest(最大生成树+并查集)
- HDU 3367 Pseudoforest(kruskal最大生成树变形)
- ThreadDeathLock
- Win7下cd命令
- linux下错误的捕获:errno和strerror的使用
- 程序员面试什么最重要?
- HDOJ 1116/POJ 1386 - Play on Words 判断有向图哈密顿通路转化为判断有向图是否存在欧拉通路
- (step6.1.8)hdu 3367(Pseudoforest——最小生成树的逆应用)
- 当你需要向用户解释时,就已经输了一半
- 中英文对照 Linux 操作系统错误代码解释
- Amazon Web Services Route 53
- UIButton inside a view that has a UITapGestureRecognizer
- e1000 napi
- Z-index属性
- Linux查看程序端口占用情况
- js 实现table自动排序