Online JudgeProblem SetAuthorsOnline ContestsUser
Web Board
Home Page
F.A.Qs
Statistical Charts
Problems
Submit Problem
Online Status
Prob.ID:
Register
Update your info
Authors ranklist
Current Contest
Past Contests
Scheduled Contests
Award Contest
User ID:
Password:
  Register

用 Prim 都过了,Kruskal 咋不行啊?

Posted by kingarthur at 2007-07-18 21:41:11 on Problem 2421
#include<stdio.h>

struct TEdge {
    int a, b, dist;
};

int N, Q, adj[1000][1000];
int UFS[1000];
struct TEdge e[1000];
int num, ans;

int cmp(struct TEdge *a, struct TEdge *b)
{
    return (a -> dist - b -> dist);
}

int root(int i)
{
    if (UFS[i] == -1)
        return (i);
    else
        return (root(UFS[i]));
}

int equal(int i, int j)
{
    return (root(i) == root(j));
}

void _union(int i, int j)
{
    UFS[root(j)] = root(i);
}

int main()
{
    int i, j, a, b;
    
    scanf("%d", &N);
    for (i = 0; i < N; i++)
        for (j = 0; j < N; j++)
            scanf("%d", &adj[i][j]);
    memset(UFS, -1, sizeof(UFS));
    scanf("%d", &Q);
    for (i = 0; i < Q; i++) {
        scanf("%d %d", &a, &b);
        if (!equal(a - 1, b - 1))
            _union(a - 1, b - 1);
    }
    
    num = 0;
    for (i = 0; i < N; i++)
        for (j = 0; j < N; j++)
            if (adj[i][j]) {
                e[num].a = i;
                e[num].b = j;
                e[num].dist = adj[i][j];
                num++;
            }
    qsort(e, num, sizeof(e[0]), cmp);
    
    ans = 0;
    for (i = 0; i < num; i++)
        if (!equal(e[i].a, e[i].b)) {
            _union(e[i].a, e[i].b);
            ans += e[i].dist;
        }
        
    printf("%d\n", ans);
    
    system("pause");
    
    return (0);
}

Followed by:

Post your reply here:
User ID:
Password:
Title:

Content:

Home Page   Go Back  To top


All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator