ZOJ 2966 Build The Electric System(最小生成树)

题目链接:http://vj.hsacm.com/problem/visitOriginUrl.action?id=74919
思路:裸prim算法 水题

#include
#include
#include
#include
#include
#include
#include
#include
#define mt(a) memset(a,0,sizeof a)
#define fl(a,b,c) fill(a,b,c)

#define inf 1000000000+7

using namespace std;

typedef long long ll;

int n, m;

ll graph[550][550];
int vis[550] ;
ll dis[550];

ll ans = 0;

ll prim()
{
    ll i, j, pos, min, result = 0;
    memset(vis, 0, sizeof vis);
    fill(dis, dis + 550, inf);
    vis[0] = 1; pos = 0;
    dis[0] = 0;
    for (i = 0; i < n; i++)
    if (i != pos) dis[i] = graph[pos][i];
    for (i = 0; i1; i++)
    {

        min = inf;
        for (j = 0; j < n; j++)
        if (vis[j] == 0 && min>dis[j])
        {
            min = dis[j]; pos = j;
        }
        result += min;
        vis[pos] = 1;
        for (j = 0; j < n; j++)
        if (vis[j] == 0 && dis[j]>graph[pos][j])
            dis[j] = graph[pos][j];
    }
    return result;
}


int main()
{
    int T;
    cin >> T;
    while (T--)
    {
        scanf("%d %d", &n, &m);
        for (int i = 0; i <= n; i++)
        {
            for (int j = 0; j <= n; j++)graph[i][j] = inf;
        }
        memset(vis, 0, sizeof vis);

        for (int i = 0; i < m; i++)
        {
            int x, y, k;
            scanf("%d %d %lld", &x, &y, &k);
            graph[x][y] = k;
            graph[y][x] = k; 
        }
        ans = prim();
        printf("%lld\n", ans);
    }
    return 0;
}

你可能感兴趣的:(ZOJ,算法,prim)