hdu 1689 求奇环bfs关键是层次图

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<queue>
using namespace std;
#define inf 0x3fffffff
#define N 1100
#define NN 21000
struct node {
int u,v,next;
}bian[NN*2];
int head[N],yong;
void init() {
memset(head,-1,sizeof(head));
yong=0;
}
void addedge(int u,int v) {
bian[yong].u=u;
bian[yong].v=v;
bian[yong].next=head[u];
head[u]=yong++;
}
struct enode{
int step,u;
};
int vis[N][2];
int n;
int bfs(int u) {
  int i;
  enode kk,cur,next;
  kk.u=u;
  kk.step=0;
  memset(vis,0,sizeof(vis));
  queue<enode>q;
  vis[u][0]=1;//刚开始时偶数
  q.push(kk);
  while(!q.empty()) {
    cur=q.front();
    q.pop();
    if(cur.step>=3) {
        if(cur.step%2==1&&cur.u==u)//最后是奇数
            return cur.step;
    }
   for(i=head[cur.u];i!=-1;i=bian[i].next) {
       int v=bian[i].v;
       next.u=v;
       next.step=cur.step+1;
    if(!vis[v][next.step%2]) {//标记一个点的奇偶是否出现过
        vis[v][next.step%2]=1;
        q.push(next);
    }
   }
  }
  return inf;
}
int main(){
    int n,m,i,k,t,u,v,minn,kk=0;
    scanf("%d",&t);
    while(t--) {
        scanf("%d%d",&n,&m);
   init();
        for(i=1;i<=m;i++) {
            scanf("%d%d",&u,&v);
           addedge(u,v);addedge(v,u);
        }
        minn=inf;
        for(i=1;i<=n;i++) {
            k=bfs(i);
            if(minn>k)
                minn=k;
                if(minn==3)break;
        }
        if(minn==inf)
            printf("Case %d: Poor JYY.\n",++kk);
        else
        printf("Case %d: JYY has to use %d balls.\n",++kk,minn);
    }
return 0;}

posted @ 2014-11-12 11:20  HYDhyd  阅读(105)  评论(0编辑  收藏  举报