题目:http://www.lydsy.com/JudgeOnline/problem.php?id=1562
大概没有人想我这么无聊一直用最大流来写二分图匹配的题目了额。。。:首先这明显是二分图匹配,那么就直接求一次最大流,然后从第一个开始贪心枚举找环,如果找得到环的话就沿着环增广就可以了,记得找环的时候把源点去掉,要不会TLE到跪。。。。
代码:
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <bitset>
using namespace std ;
#define inf 0x7fffffff
#define maxn 20010
struct edge {
edge *next , *pair ;
int t , f ;
} *head[ maxn ] ;
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 , 0 ) ;
head[ s ] -> pair = head[ t ] , head[ t ] -> pair = head[ s ] ;
}
int h[ maxn ] , gap[ maxn ] , S , T ;
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 ] = T ;
gap[ ++ h[ v ] ] ++ , d[ v ] = head[ v ] ;
return rec ;
}
int maxflow( ) {
memset( gap , 0 , sizeof( gap ) ) ;
memset( h , 0 , sizeof( h ) ) ;
gap[ S ] = T ;
for ( int i = 0 ; i ++ < T ; ) d[ i ] = head[ i ] ;
int flow = 0 ;
for ( ; h[ S ] < T ; flow += sap( S , inf ) ) ;
return flow ;
}
int n , ans[ maxn ] ;
bool flag ;
edge *P[ maxn ] ;
bitset < maxn > f , vi ;
void dfs( int v , int u ) {
f[ v ] = true ;
for ( P[ v ] = head[ v ] ; P[ v ] ; P[ v ] = P[ v ] -> next ) if ( P[ v ] -> f && ! vi[ P[ v ] -> t ] ) {
if ( ! f[ P[ v ] -> t ] ) dfs( P[ v ] -> t , u ) ;
else if ( P[ v ] -> t == u ) flag = true ;
if ( flag ) {
P[ v ] -> f ^= 1 , P[ v ] -> pair -> f ^= 1 ;
break ;
}
}
f[ v ] = false , vi[ v ] = true ;
}
int main( ) {
scanf( "%d" , &n ) ;
S = 2 * n + 1 ; T = S + 1 ;
memset( head , 0 , sizeof( head ) ) ;
for ( int i = 0 ; i ++ < n ; ) {
int x ; scanf( "%d" , &x ) ;
int l = i - x , r = i + x ;
if ( r > n ) r -= n ;
if ( l <= 0 ) l += n ;
AddEdge( S , i , 1 ) , AddEdge( n + i , T , 1 ) ;
AddEdge( i , n + l , 1 ) , AddEdge( i , n + r , 1 ) ;
}
if ( maxflow( ) == n ) {
f.reset( ) ;
for ( int i = 0 ; i ++ < n ; ) {
edge *x = head[ i ] , *y = head[ i ] -> next ;
if ( x -> t > y -> t ) swap( x , y ) ;
if ( ! x -> f ) {
x -> pair -> f = 0 , ans[ i ] = x -> t - n - 1 ;
} else {
flag = false ;
vi.reset( ) ; vi[ S ] = true ;
dfs( i , i ) ;
if ( flag ) {
ans[ i ] = x -> t - n - 1 , x -> pair -> f = 0 ;
} else {
ans[ i ] = y -> t - n - 1 , y -> pair -> f = 0 ;
}
}
}
for ( int i = 0 ; i ++ < n - 1 ; ) printf( "%d " , ans[ i ] ) ;
printf( "%d\n" , ans[ n ] ) ;
} else printf( "No Answer\n" ) ;
return 0 ;
}
网友评论