UVa 10600 ACM contest and Blackout( 次小生成树)

很裸的模板题

求最小生成树,和次小生成树

代码:

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

const int N = 110;
const int M = 310;
const int INF = 100000000;
int n, m, map[N][N], p[N], d[N], f[N][N], s1, s2, mark[N];
void prim() {
    for ( int i = 1; i <= n; ++i ) p[i] = -1, d[i] = INF;
    int mi, v;
    bool vis[N];
    memset(vis, 0, sizeof(vis));
    d[1] = 0, s1 = 0;
    for ( int u = 0; u < n; ++u ) {
        mi = INF;
        for ( int i = 1; i <= n; ++i ) if ( !vis[i] && mi > d[i] ) mi = d[i], v = i;
        s1 += mi;
        vis[v] = true;
        for ( int i = 1; i <= n; ++i ) if ( !vis[i] && d[i] > map[v][i] ) d[i] = map[v][i], p[i] = v;
    }
}
void dfs( int v ) {
    for ( int u = 1; u <= n; ++u ) {
        if ( !mark[u] && p[u] == v && u != v ) {
            mark[u] = true;
            for ( int x = 1; x <= n; ++x ) if ( mark[x] && u != x ) {
               f[x][u] = f[u][x] = max( f[x][v], map[u][v] ); 
            }
            dfs(u);
        }
    }
}
int main() {
    int T;
    scanf("%d", &T);
    while ( T-- ) {
        scanf("%d%d", &n, &m);
        for ( int i = 1; i <= n; ++i ) 
            for ( int j = 1; j <= n; ++j ) map[i][j] = INF;
        while ( m-- ) {
            int a, b, c;
            scanf("%d%d%d", &a, &b, &c);
            map[a][b] = map[b][a] = c;
        }
        prim();
        memset( f, 0, sizeof(f));
        memset( mark, 0, sizeof(mark));
        mark[1] = true;
        dfs( 1 );
        s2 = INF;
        /*for ( int i = 1; i <= n; ++i ) {
            for ( int j = 1; j <= n; ++j ) 
                printf("%d ", f[i][j] );
            printf("\n");
        }*/
        for ( int i = 1; i <= n; ++i ) 
            for ( int j = i+1; j <= n; ++j ) {
                if ( j != p[i] && i != p[j] ) {
                    s2 = ( s2 <= s1 - f[i][j] + map[i][j] ? s2 : s1 - f[i][j] + map[i][j] ); 
                }
            }
        printf("%d %d\n", s1, s2);
    }
}




你可能感兴趣的:(UVa 10600 ACM contest and Blackout( 次小生成树))