题意:给定n个点,m条无向边。
首先判断能否得到一个二分图(BFS),如果可以,则进行二分图匹配。
View Code
1 #include<stdio.h> 2 #include<string.h> 3 #include<stdlib.h> 4 #include<queue> 5 #include<algorithm> 6 using namespace std; 7 const int maxn = 205; 8 const int maxm = 205*205; 9 struct node{ 10 int u,val,next; 11 }edge[ maxm*2 ]; 12 int head[ maxn ],color[ maxn ]; 13 int cnt; 14 int fa[ maxn ],vis[ maxn ]; 15 16 void init(){ 17 cnt=0; 18 memset( head,-1,sizeof(head)); 19 memset( fa,-1,sizeof(fa) ); 20 } 21 void addedge( int a,int b,int c ){ 22 edge[ cnt ].u=b; 23 edge[ cnt ].val=c; 24 edge[ cnt ].next=head[ a ]; 25 head[ a ]=cnt++; 26 } 27 int n,m; 28 29 int bfs( ){ 30 int now,next; 31 queue<int>q; 32 q.push( 1 ); 33 memset( color,-1,sizeof( color )); 34 color[ 1 ]=1; 35 while( !q.empty() ){ 36 now=q.front(),q.pop(); 37 int next_color=1-color[ now ]; 38 for( int i=head[ now ];i!=-1;i=edge[ i ].next ){ 39 next=edge[ i ].u; 40 if( color[ next ]==-1 ){ 41 color[ next ]=next_color; 42 q.push( next ); 43 } 44 else if( color[ next ]==color[ now ] ) return 1; 45 } 46 } 47 return 0; 48 } 49 50 int dfs( int now ){ 51 for( int i=head[ now ];i!=-1;i=edge[ i ].next ){ 52 int next=edge[ i ].u; 53 if( vis[ next ]==1 ) continue; 54 vis[ next ]=1; 55 if( fa[ next ]==-1||dfs( fa[ next ] ) ){ 56 fa[ next ]=now; 57 return 1; 58 } 59 } 60 return 0; 61 } 62 63 int main(){ 64 while( scanf("%d%d",&n,&m)==2 ){ 65 int a,b; 66 init(); 67 while( m--){ 68 scanf("%d%d",&a,&b); 69 addedge( a,b,1 ); 70 addedge( b,a,1 ); 71 } 72 if( bfs()==1 ) {//判断是否能形成二分图 73 printf("No\n"); 74 continue; 75 } 76 int ans=0; 77 for( int i=1;i<=n;i++ ){ 78 memset( vis,0,sizeof(vis) ); 79 ans+=dfs( i ); 80 //if( dfs(i)==1 ) printf("i:%d fa[%d]=%d\n",i,i,fa[i]); 81 } 82 printf("%d\n",ans/2); 83 } 84 return 0; 85 }