传送门:【HDU】3879 Base Station
题目分析:最大权闭合子图。。。所有公司向汇点建边,容量为花费,每条边用一个点表示,源点向这条边代表的点建边,容量为利益,这个点向代表的边的头尾建边,容量为INF。跑一遍最大流,边的利益总和减去最小割就是答案。
代码如下:
#include <cstdio> #include <cstring> #include <algorithm> using namespace std ; #define REP( i , a , b ) for ( int i = a ; i < b ; ++ i ) #define REV( i , a , b ) for ( int i = a - 1 ; i >= b ; -- i ) #define FOR( i , a , b ) for ( int i = a ; i <= b ; ++ i ) #define FOV( i , a , b ) for ( int i = a ; i >= b ; -- i ) #define CLR( a , x ) memset ( a , x , sizeof a ) #define CPY( a , x ) memcpy ( a , x , sizeof a ) const int MAXN = 55005 ; const int MAXQ = 55005 ; const int MAXE = 1000005 ; const int INF = 0x3f3f3f3f ; struct Edge { int v , n , c ; Edge () {} Edge ( int v , int c , int n ) : v ( v ) , c ( c ) , n ( n ) {} } ; struct Net { Edge E[MAXE] ; int H[MAXN] , cntE ; int d[MAXN] , num[MAXN] , cur[MAXN] , pre[MAXN] ; int Q[MAXQ] , head , tail ; int s , t , nv ; int n , m ; int flow ; void init () { cntE = 0 ; CLR ( H , -1 ) ; } void addedge ( int u , int v , int c ) { E[cntE] = Edge ( v , c , H[u] ) ; H[u] = cntE ++ ; E[cntE] = Edge ( u , 0 , H[v] ) ; H[v] = cntE ++ ; } void rev_bfs () { CLR ( d , -1 ) ; CLR ( num , 0 ) ; head = tail = 0 ; Q[tail ++] = t ; d[t] = 0 ; num[d[t]] = 1 ; while ( head != tail ) { int u = Q[head ++] ; for ( int i = H[u] ; ~i ; i = E[i].n ) { int v = E[i].v ; if ( ~d[v] ) continue ; d[v] = d[u] + 1 ; num[d[v]] ++ ; Q[tail ++] = v ; } } } int ISAP () { CPY ( cur , H ) ; rev_bfs () ; flow = 0 ; int u = pre[s] = s ; while ( d[s] < nv ) { if ( u == t ) { int f = INF , pos ; for ( int i = s ; i != t ; i = E[cur[i]].v ) if ( f > E[cur[i]].c ) { f = E[cur[i]].c ; pos = i ; } for ( int i = s ; i != t ; i = E[cur[i]].v ) { E[cur[i]].c -= f ; E[cur[i] ^ 1].c += f ; } flow += f ; u = pos ; } for ( int &i = cur[u] ; ~i ; i = E[i].n ) if ( E[i].c && d[u] == d[E[i].v] + 1 ) break ; if ( ~cur[u] ) { pre[E[cur[u]].v] = u ; u = E[cur[u]].v ; } else { if ( 0 == ( -- num[d[u]] ) ) break ; int mmin = nv ; for ( int i = H[u] ; ~i ; i = E[i].n ) if ( E[i].c && mmin > d[E[i].v] ) { cur[u] = i ; mmin = d[E[i].v] ; } d[u] = mmin + 1 ; num[d[u]] ++ ; u = pre[u] ; } } return flow ; } void solve () { int sum = 0 ; int u , v , c ; init () ; s = 0 ; t = n + m + 1 ; nv = t + 1 ; FOR ( i , 1 , n ) { scanf ( "%d" , &c ) ; addedge ( i , t , c ) ; } FOR ( i , 1 , m ) { scanf ( "%d%d%d" , &u , &v , &c ) ; addedge ( s , i + n , c ) ; addedge ( i + n , u , INF ) ; addedge ( i + n , v , INF ) ; sum += c ; } printf ( "%d\n" , sum - ISAP () ) ; } } x ; int main () { while ( ~scanf ( "%d%d" , &x.n , &x.m ) ) x.solve () ; return 0 ; }