BZOJ-2561: 最小生成树(最小割)

题目:http://www.lydsy.com/JudgeOnline/problem.php?id=2561

没什么好说的,两遍最小割完事。。。

代码:

#include <cstdio>
#include <algorithm>
#include <cstring>
 
using namespace std ;
 
const int maxn = 20100 , inf = 0x7fffffff , maxm = 200010 ;
 
struct network {
    struct edge {
        edge *next , *pair ;
        int t , f ;
    } *head[ maxn ] ;
    void Init(  ) {
        memset( head , 0 , sizeof( head ) ) ;
    }
    void Add( int s , int t , int f ) {
        edge *p = new( edge ) ;
        p -> t = t , p -> f = f , p -> next = head[ s ] ;
        head[ s ] = p ;
    }
    void AddEdge( int s , int t , int f ) {
        Add( s , t , f ) , Add( t , s , f ) ;
        head[ s ] -> pair = head[ t ] , head[ t ] -> pair = head[ s ] ;
    }
    int gap[ maxn ] , h[ maxn ] , S , T , V ;
    edge *d[ maxn ] ;
    int sap( int v , int flow ) {
        if ( v == T ) return flow ;
        int rec = 0 ; 
        for ( edge *p = d[ v ] ; p ; p = p -> next ) if ( p -> f && h[ v ] == h[ p -> t ] + 1 ) {
            int ret = sap( p -> t , min( flow - rec , p -> f ) ) ;
            p -> f -= ret , p -> pair -> f += ret , d[ v ] = p ;
            if ( ( rec += ret ) == flow ) return flow ;
        }
        if ( ! ( -- gap[ h[ v ] ] ) ) h[ S ] = V ;
        gap[ ++ h[ v ] ] ++ , d[ v ] = head[ v ] ;
        return rec ;
    }
    int maxflow(  ) {
        int flow = 0 ; 
        for ( int i = 0 ; i ++ < V ; ) {
            h[ i ] = gap[ i ] = 0 , d[ i ] = head[ i ] ;
        }
        gap[ 0 ] = V ;
        for ( ; h[ S ] < V ; flow += sap( S , inf ) ) ;
        return flow ;
    }
} net ;
 
int n , m , E[ maxm ][ 3 ] , u , v , l , ans ;
 
int main(  ) {
    scanf( "%d%d" , &n , &m ) ;
    for ( int i = 0 ; i ++ < m ; ) scanf( "%d%d%d" , &E[ i ][ 0 ] , &E[ i ][ 1 ] , &E[ i ][ 2 ] ) ;
    scanf( "%d%d%d" , &u , &v , &l ) ;
    net.Init(  ) ;
    net.S = u , net.T = v , net.V = n ;
    for ( int i = 0 ; i ++ < m ; ) if ( E[ i ][ 2 ] < l ) {
        net.AddEdge( E[ i ][ 0 ] , E[ i ][ 1 ] , 1 ) ;
    }
    ans = net.maxflow(  ) ;
    net.Init(  ) ;
    for ( int i = 0 ; i ++ < m ; ) if ( E[ i ][ 2 ] > l ) {
        net.AddEdge( E[ i ][ 0 ] , E[ i ][ 1 ] , 1 ) ;
    }
    printf( "%d\n" , ans += net.maxflow(  ) ) ;
    return 0 ; 
}
    原文作者:AmadeusChan
    原文地址: https://www.jianshu.com/p/72633626aac9
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞