码迷,mamicode.com
首页 > 其他好文 > 详细

[2016-01-27][UVA][1395][D -?Slim Span]

时间:2016-01-28 00:40:12      阅读:224      评论:0      收藏:0      [点我收藏+]

标签:

[2016-01-27][UVA][1395][D - Slim Span]

  • 时间:2016-01-21  11:06:30  星期四
  • 题目编号:UVA 1395
  • 题目大意:求所有生成树 最大边和最小边之差的最小值
  • 分析:
    • 想法是枚举所有边,但是分析之后发现可以不用枚举所有的树
    • 已知krukal得到的最小生成树得到的最小生成树,最大边最小
    • 也就是说,这个最大边,就是使得 最大边和最小边 差值最大的边
    • 那么,只需要求每条边的对应的差值最小的最大边即可
  • 方法:
    • 从最小的边开始跑生成树,然后跑kruskal生成树,
    • 取所有生成树最小的差值即可
  • 解题过程遇到问题:
    • 最小生成树 能保证最大边最小,最小边最小  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <queue>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cctype>
#include <string>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
using namespace std;
const int maxn = 110;
int n,m;
 
struct Edge{
    int u,v;
    long long c;
    bool operator < (const Edge & a)const
    {
        return c < a.c;
    }
}e[maxn*maxn/2];
 
int fa[maxn];
 
void ini(){
    for(int i = 0;i < n + 5;i++)
        fa[i] = i;
}
 
int fnd(int x){
    return x == fa[x] ? x : (fa[x] = fnd(fa[x]));
}
vector<Edge> chs;
long long  kruskal()
{
    sort(e,e + m);
    long long  k = -1;
    for(int j = 0;j < m;j++)
    {
        int ct = 0;
        long long res = 0;
        ini();
        chs.clear();
        for(int i = j;i < m;i++)
        {
            if(ct == n - 1)
                break;
            int u = e[i].u,v = e[i].v;
            u = fnd(u);
            v = fnd(v);
            if(u != v)
            {
                fa[u] = v;
                res += e[i].c;
                chs.push_back(e[i]);
                ct++;
            }
        }
        if(ct == n-1 && (k > chs[chs.size() - 1].c -  chs[0].c  || k == -1))
            k = chs[chs.size() - 1].c -  chs[0].c;
    }
    return k;
}
int main()
{
    //freopen("out.txt","w",stdout);
    while(~scanf("%d%d",&n,&m) && (m || n))
    {
        int a,b,c;
        for(int i = 0;i < m;i++)
        {
            scanf("%d%d%d",&a,&b,&c);
            e[i].u =a;
            e[i].v =b;
            e[i].c =c;
        }
        printf("%lld\n",kruskal());
    }
    return 0;
}







[2016-01-27][UVA][1395][D -?Slim Span]

标签:

原文地址:http://www.cnblogs.com/qhy285571052/p/5164901.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!