【HDU】5313 Bipartite Graph【二分图+背包】

传送门:【HDU】5313 Bipartite Graph

复杂度: O(NNlogN32)
方法:多重背包bitset优化

my  code:

#include <stdio.h>
#include <string.h>
#include <bitset>
#include <algorithm>
using namespace std ;

typedef long long LL ;

#define clr( a , x ) memset ( a , x , sizeof a )

const int MAXN = 10005 ;
const int MAXM = 10000005 ;
const int MAXE = 200005 ;
const int INF = 0x3f3f3f3f ;

struct Edge {
    int v , n ;
    Edge () {}
    Edge ( int v , int n ) : v ( v ) , n ( n ) {}
} ;

Edge E[MAXE] ;
int H[MAXN] , cntE ;
bitset < MAXN > f ;
int cnt[MAXN] ;
int vis[MAXN] ;
int c[3] ;
int n , m ;
int V ;

void init () {
    cntE = 0 ;
    clr ( H , -1 ) ;
}

void addedge ( int u , int v ) {
    E[cntE] = Edge ( v , H[u] ) ;
    H[u] = cntE ++ ;
}

void dfs ( int u ) {
    c[vis[u]] ++ ;
    for ( int i = H[u] ; ~i ; i = E[i].n ) {
        int v = E[i].v ;
        if ( !vis[v] ) {
            vis[v] = 3 - vis[u] ;
            dfs ( v ) ;
        }
    }
}


void scanf ( int& x , char c = 0 ) {
    while ( ( c = getchar () ) < '0' ) ;
    x = c - '0' ;
    while ( ( c = getchar () ) >= '0' ) x = x * 10 + c - '0' ;
}

void solve () {
    int u , v ;
    int L = 0 , R = 0 ;
    init () ;
    clr ( cnt , 0 ) ;
    clr ( vis , 0 ) ;
    f.reset () ;
    scanf ( n ) ;
    scanf ( m ) ;
    for ( int i = 1 ; i <= m ; ++ i ) {
        scanf ( u ) ;
        scanf ( v ) ;
        addedge ( u , v ) ;
        addedge ( v , u ) ;
    }
    for ( int i = 1 ; i <= n ; ++ i ) if ( !vis[i] ) {
        vis[i] = 1 ;
        c[1] = c[2] = 0 ;
        dfs ( i ) ;
        if ( c[1] > c[2] ) swap ( c[1] , c[2] ) ;
        L += c[1] ;
        R += c[2] - c[1] ;
        cnt[c[2] - c[1]] ++ ;
    }
    f[0] = 1 ;
    for ( int i = 1 ; i <= n ; ++ i ) if ( cnt[i] ) {
        for ( int k = 1 ; k < cnt[i] ; cnt[i] -= k , k <<= 1 ) f |= f << ( i * k ) ;
        f |= f << ( i * cnt[i] ) ;
    }
    int t = R / 2 ;
    R += L ;
    for ( int i = t ; i <= n ; ++ i ) if ( f[i] ) {
        printf ( "%d\n" , ( L + i ) * ( R - i ) - m ) ;
        return ;
    }
}

int main () {
    int T ;
    scanf ( T ) ;
    for ( int i = 1 ; i <= T ; ++ i ) {
        solve () ;
    }
    return 0 ;
}

你可能感兴趣的:(【HDU】5313 Bipartite Graph【二分图+背包】)