UVa 10842 Traffic Flow(最大生成树)

这道题,第一wa了,因为我没有注意它可能是存在自环以及重边的

很水的一道最大生成树的题

代码如下:

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

const int N = 110;
const int INF = -1;
const int INFB = 10000;
int T, n, m, g[N][N], p[N], pa;
void prim() {
    int d[N], v, mi;
    bool vis[N];
    for ( int i = 0; i <= n; ++i ) d[i] = p[i] = -1;
    memset(vis, 0, sizeof(vis));
    d[0] = 0, pa = 0;
    for ( int u = 0; u < n; ++u ) {
        mi = INF;
        for ( int i = 0; i < n; ++i ) if ( !vis[i] && d[i] > mi ) mi = d[i], v = i;
        vis[v] = true;
        pa += mi;
        for ( int i = 0; i < n; ++i ) if ( !vis[i] && d[i] < g[v][i] ) p[i] = v, d[i] = g[v][i];
    }
}

int main()
{
    int idx = 1;
    scanf("%d", &T);
    while( T-- ) {
        scanf("%d%d", &n, &m);
        for ( int i = 0; i < n; ++i ) for ( int j = 0; j < n; ++j ) g[i][j] = -1;
        while ( m-- ){
            int a, b, c;
            scanf("%d%d%d", &a, &b, &c);
            if ( a != b )
                g[a][b] = g[b][a] = max( c, g[a][b] );
        }
        prim();
        int ans = INFB; 
        for ( int i = 1; i < n; ++i ) 
            ans = min( ans, g[i][p[i]] );
        printf("Case #%d: %d\n", idx++, ans);
    }
}



你可能感兴趣的:(UVa 10842 Traffic Flow(最大生成树))