wqy的ACM赛G朱柏庐

建虚点,点权看作是从虚点连向实点的边权.
对整个图和虚点跑最小生成树即可.

#include <algorithm>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <string>
#include <vector>
#include <queue>
#include <cmath>
#include <ctime>
#include <map>
#include <set>
#define MEM(x,y) memset ( x , y , sizeof ( x ) )
#define rep(i,a,b) for (int i = (a) ; i <= (b) ; ++ i)
#define per(i,a,b) for (int i = (a) ; i >= (b) ; -- i)
#define pii pair < int , int >
#define one first
#define two second
#define rint read<int>
#define pb push_back
#define db double

using std::queue ;
using std::set ;
using std::pair ;
using std::max ;
using std::min ;
using std::priority_queue ;
using std::vector ;
using std::swap ;
using std::sort ;
using std::unique ;
using std::greater ;

template < class T >
    inline T read () {
        T x = 0 , f = 1 ; char ch = getchar () ;
        while ( ch < '0' || ch > '9' ) {
            if ( ch == '-' ) f = - 1 ;
            ch = getchar () ;
        }
       while ( ch >= '0' && ch <= '9' ) {
            x = ( x << 3 ) + ( x << 1 ) + ( ch - 48 ) ;
            ch = getchar () ;
       }
       return f * x ;
}

const int N = 1e5 + 100 ;
const int M = 2e5 + 100 ;

struct edge {
    int to , next , data , from ;
    friend bool operator < (edge a , edge b) { return a.data < b.data ; }
} e[M<<1] ;

int n , m , vir , tot , head[M] , f[M] ;
long long ans ;

inline void build (int u , int v , int w) {
    e[++tot].next = head[u] ; e[tot].to = v ; e[tot].from = u ;
    e[tot].data = w ; head[u] = tot ; return ;
}

inline int getf (int x) { return f[x] == x ? x : f[x] = getf ( f[x] ) ; }

signed main (int argc , char * argv[]) {
    n = rint () ; m = rint () ; vir = n + 1 ;
    rep ( i , 1 , n ) {
        int x = rint () ;
        build ( vir , i , x ) ;
        // build ( i , vir , x ) ;
    }
    rep ( i , 1 , m ) {
        int u = rint () , v = rint () , w = rint () ;
        build ( u , v , w ) ; // build ( v , u , w ) ;
    }
    sort ( e + 1 , e + tot + 1 ) ;
    rep ( i , 1 , n << 1 ) f[i] = i ;
    int k = 0 ; rep ( i , 1 , tot ) {
        int u = getf ( e[i].from ) , v = getf ( e[i].to ) ;
        if ( u != v ) {
            ++ k ; f[v] = u ;
            ans += e[i].data ;
        }
        if ( k >= n ) break ;
    }
    printf ("%lld
" , ans ) ;
    system ("pause") ; return 0 ;
}
原文地址:https://www.cnblogs.com/Equinox-Flower/p/11649994.html