题意:给定一张无向图,求最小的奇数环。
注意:状态的设定 vis[ i ][ 0 ] and vis[ i ][ 1 ] 很重要!!!
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 /* 2 BFS+最小奇数环 3 */ 4 #include<stdio.h> 5 #include<string.h> 6 #include<stdlib.h> 7 #include<algorithm> 8 #include<iostream> 9 #include<queue> 10 #include<stack> 11 #include<math.h> 12 #include<map> 13 using namespace std; 14 const int maxn = 1005; 15 const int maxm = 40005; 16 const int inf = 0x7fffffff; 17 int head[ maxn ],cnt; 18 struct node{ 19 int u,next; 20 }edge[ maxm ]; 21 int dis[ maxn ],vis[ maxn ][ 2 ];//vis[ i ][ 0 ],在i点偶数步;dis[ i ]仅代表i的 lev !! 22 int mat[ maxn ][ maxn ]; 23 int ans; 24 void init(){ 25 memset( head,-1,sizeof( head )); 26 cnt=0; 27 memset( mat,-1,sizeof( mat ) ); 28 ans=inf; 29 } 30 void addedge( int a,int b ){ 31 edge[ cnt ].u=b; 32 edge[ cnt ].next=head[ a ]; 33 head[ a ]=cnt++; 34 } 35 void bfs( int s,int n ){ 36 memset( vis,0,sizeof( vis ) ); 37 for( int i=1;i<=n;i++ ) 38 dis[ i ]=inf; 39 queue<int>q; 40 q.push( s ); 41 vis[ s ][ 0 ]=1; 42 dis[ s ]=0; 43 //printf("bfs\n"); 44 while( !q.empty() ){ 45 int now=q.front(); 46 //printf("now:%d\n",now); 47 q.pop(); 48 if( vis[ s ][ (dis[s]%2) ]==1 && (dis[ s ]%2)==1 && dis[ s ]>=3 ){ 49 ans=min( ans,dis[ s ] ); 50 } 51 for( int i=head[ now ];i!=-1;i=edge[ i ].next ){ 52 int nxt=edge[ i ].u; 53 //if( dis[ nxt ]>dis[ now ]+1 ){ 54 // dis[ nxt ]=dis[ now ]+1; 55 if( vis[ nxt ][ ((dis[ now ]+1)%2) ]==0 ){ 56 vis[ nxt ][ ((dis[ now ]+1)%2) ]=1; 57 dis[ nxt ]=dis[ now ]+1; 58 q.push( nxt ); 59 } 60 // } 61 } 62 } 63 } 64 65 int main(){ 66 int ca; 67 scanf("%d",&ca); 68 for( int tca=1;tca<=ca;tca++ ){ 69 int n,m; 70 init(); 71 scanf("%d%d",&n,&m); 72 int a,b; 73 while( m-- ){ 74 scanf("%d%d",&a,&b); 75 addedge( a,b ); 76 addedge( b,a ); 77 mat[a][b]=mat[b][a]=1; 78 } 79 printf("Case %d: ",tca); 80 if( n<=2 ){ 81 printf("Poor JYY.\n"); 82 continue; 83 } 84 for( int s=1;s<=n;s++ ){ 85 bfs( s,n ); 86 //printf("ans:%d\n",ans); 87 if( ans==3 ) 88 break; 89 } 90 if( ans==inf ) 91 printf("Poor JYY.\n"); 92 else 93 printf("JYY has to use %d balls.\n",ans); 94 } 95 return 0; 96 }