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

poj2395 Out of Hay , 求MST的最长边

时间:2014-06-11 06:45:17      阅读:235      评论:0      收藏:0      [点我收藏+]

标签:style   class   blog   code   http   tar   

点击打开链接


求MST的最长边~


prim

#include <cstdio>
#include <cstring>
#include <vector>
#include <algorithm>
#define Min(a,b) (a)<(b)?(a):(b)
using namespace std;

const int INF = 1000000000;
const int maxn = 2000 + 5;

struct pto
{
    int v, len;
};

vector<pto> G[maxn];
bool vis[maxn];
int dis[maxn];
int n, m;

int Prim()
{
    int i, j, p, ans, minc;
    memset(vis, 0, sizeof vis );
    for(i=1; i<=n; ++i) dis[i] = INF;
    dis[1] = 0;
    ans = 0;
    int maxx = -100;
    for(i=1; i<=n; ++i)
    {
        minc = INF, p = -1;
        for(j=1; j<=n; ++j) if(!vis[j])
            if(minc>dis[j]) minc = dis[p=j];
        if(-1 == p) break;
        vis[p] = 1;
        if(maxx <minc) maxx = minc;
        for(j=0; j<G[p].size(); ++j) if(!vis[G[p][j].v])
        {
            int& u = G[p][j].v;
            dis[u] = Min(dis[u], G[p][j].len);
        }
    }
    return maxx;
}




int main()
{
    int i, x, y, z;
    pto e;
    while(~scanf("%d%d",&n,&m))
    {
        for(i=0; i<=n; ++i) G[i].clear();
        for(i=0; i<m; ++i)
        {
            scanf("%d%d%d",&x,&y,&z);
            e.v = y, e.len = z;
            G[x].push_back(e);
            e.v = x;
            G[y].push_back(e);
        }
        printf("%d\n",Prim());
    }
    return 0;
}

kruskal
#include <cstdio>
#include <cstring>
#include <vector>
#include <algorithm>
using namespace std;

const int INF = 1000000000;
const int maxn = 2000 + 5;
const int maxm = 10000 + 5;

struct Edge {
    int x, y, w;
    Edge(int x=0, int y=0, int w=0):x(x),y(y),w(w) {}
    bool operator < (const Edge& rhs) const {
        return w < rhs.w;
    }
} e[maxm];
int fa[maxn];
int n, m;

int getfather(int x)
{
    while(x != fa[x])
        x = fa[x];
    return fa[x];
}

int kruskal()
{
    int i, t1, t2, ans = 0, num = 0;
    int maxx = -100;
    sort(e, e+m);
    for(i=1; i<=n; ++i) fa[i] = i;
    for(i=0; i<m; ++i) {
        t1 = getfather(e[i].x);
        t2 = getfather(e[i].y);
        if(t1 != t2) {
            fa[t1] = t2;
            ans += e[i].w;
            if(maxx<e[i].w) maxx = e[i].w;
            if(++num==n-1) break;
        }
    }
    return maxx;
}

int main()
{
    int i, x, y, z;
    while(~scanf("%d%d",&n,&m)) {
        for(i=0; i<m; ++i) {
            scanf("%d%d%d",&e[i].x, &e[i].y, &e[i].w);
        }
        printf("%d\n", kruskal());
    }
    return 0;
}


poj2395 Out of Hay , 求MST的最长边,布布扣,bubuko.com

poj2395 Out of Hay , 求MST的最长边

标签:style   class   blog   code   http   tar   

原文地址:http://blog.csdn.net/yew1eb/article/details/29373875

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