HDOJ-1233 还是畅通工程(最小生成树)

Prime算法:

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <vector>
#include <climits>
#include <set>

using namespace std;
#define maxn 105
int Graph[maxn][maxn];
int dis[maxn], num[maxn];
int main()
{
// freopen("in.txt", "r", stdin);
    int n;

    while(scanf("%d", &n) == 1 && n)
    {
        for(int i = 1; i <= n*(n-1)/2; i++)
        {
            int a, b, c;

            scanf("%d%d%d", &a, &b, &c);
            Graph[a][b] = Graph[b][a] = c;
        }
        memset(num, 0, sizeof(num));
        for(int i = 2; i <= n; i++)
           dis[i] = Graph[1][i];
        num[1] = 1;
        int k = 1, sum = 0;;
        for(int i = 2; i <= n; i++)
        {
            int mins = INT_MAX, p;
            for(int j = 2; j <= n; j++)
            {
                if(!num[j] && mins > dis[j])
                {
                    p = j;
                    mins = dis[j];
                }
            }
            k = p;
            sum += mins;
            num[k] = 1;
            for(int j = 2; j <= n; j++)
            {
                if(!num[j] && Graph[k][j] < dis[j])
                {
                    dis[j] = Graph[k][j];
                }
            }
        }
        cout << sum << endl;
    } 

    return 0;
}

Kruskal算法

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>

using namespace std;
#define maxn 105

struct Edge{
    friend bool operator < (const Edge &a, const Edge &b)
    {
        return a.d < b.d;
    } 
    int x, y, d;
}edge[5005];
int p[maxn];

int found(int k)
{
    int s = k;
    while(s != p[s])
      s = p[s];

    int j;
    while(k != p[k])
    {
        j = p[k];
        p[k] = s;
        k = j;
    }

    return s;
}
int main()
{
    //freopen("in.txt", "r", stdin);
    int n;

    while(scanf("%d", &n) == 1 && n)
    {
        for(int i = 1; i <= n*(n-1)/2; i++)
        {
            int a, b, c;

            scanf("%d%d%d", &a, &b, &c);
            edge[i].x = a;
            edge[i].y = b;
            edge[i].d = c;
        }
        for(int i = 1; i <= n; i++)
          p[i] = i;
        sort(edge+1, edge+n*(n-1)/2+1);
        int cnt = 0, sum = 0;
        for(int i = 1; i <= n*(n-1)/2 && cnt != n-1; i++)
        {
            int k1 = found(edge[i].x), k2 = found(edge[i].y);
            if(k1 != k2)
            {
                cnt++;
                sum += edge[i].d;
                p[k1] = k2;
            }        
        }
        cout << sum << endl;
    }

    return 0;
}

你可能感兴趣的:(HDOJ-1233 还是畅通工程(最小生成树))