数据结构OJ作业——最小生成树

poj2485 Highways : http://poj.org/problem?id=2485

最小生成树输出最大边权

#include 
#include 
#include 
using namespace std;
const int MAXN = 510;
const int INF = 0x3f3f3f3f;
int map[MAXN][MAXN];
int n;
int visit[MAXN];

inline int Min(int a, int b)
{
    return a > b? b : a;
}

int prim(void)
{
    int ans = 0;
    int lowcost[MAXN];
    memset(visit,0,sizeof(visit));
    for (int i = 2; i <= n; i ++) {
        lowcost[i] = map[1][i];
    }
    lowcost[1] = 0;
    visit[1] = 1;
    for (int i = 1; i < n; i ++) {
        int min = INF, minid;
        for (int j = 1; j <= n ; j ++) {
            if (!visit[j] && lowcost[j] < min) {
                min = lowcost[j];
                minid = j;
            }
        }
        visit[minid] = 1;
        if (ans < lowcost[minid]) {
            ans = lowcost[minid];
        }
        for (int j = 1; j <= n ; j ++) {
            lowcost[j] = Min(lowcost[j], map[minid][j]);
        }
    }
    return ans;
}

int main(int argc, char const *argv[])
{
    int t;
    scanf("%d",&t);
    while (t --) {
        scanf("%d",&n);
        for (int i = 1; i <= n; i ++) {
            for (int j = 1; j <= n; j ++) {
                scanf("%d",&map[i][j]);
            }
        }
        int ans = prim();
        printf("%d\n",ans);
    }

    return 0;
}

poj2377 Bad Cowtractors : http://poj.org/problem?id=2377

最大生成树,和最小生成树是一样的

#include 
#include 
#include 
#include 
using namespace std;
int n, m, father[1005];
struct edge {
    int u,v,w;
} e[20005];

int find(int x)
{
    while (x != father[x]) {
        father[x] = father[father[x]];
        x = father[x];
    }
    return x;
}
void merge(int x, int y)
{
    x = find(x);
    y = find(y);
    if (x != y) {
        father[x] = y;
    }
    return ;
}
bool cmp(const edge &e1, const edge &e2)
{
    return e1.w > e2.w;
}
int main()
{
    while (~scanf("%d%d",&n,&m)) {
        for (int i = 1; i <= n; i ++) {
            father[i] = i;
        }
        int u, v, w;
        for (int i = 1; i <= m; i ++) {
            scanf("%d%d%d",&e[i].u, &e[i].v, &e[i].w);
        }
        sort(e + 1, e + 1 + m, cmp);
        int cnt = 0, ans = 0;
        for (int i = 1; i <= m; i ++) {
            if (find(e[i].u) != find(e[i].v) ){
                merge(e[i].u, e[i].v);
                ans += e[i].w;
                cnt ++;
            }
            if (cnt >= n - 1) break; 
        }
        if (cnt >= n - 1)
            printf("%d\n", ans);
        else 
            puts("-1");
    }

    return 0;
}

你可能感兴趣的:(数据结构)