Time Limit: 2000MS Memory limit: 65536K
提交 状态
#include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX 1000100 typedef int Status; typedef struct { int vexnum,arcnum; }MGraph; Status visited[MAX],step[MAX],top,flag,n,k; typedef struct QNode { int data; struct QNode *next; }QNode,*QueuePtr; typedef struct { QueuePtr front; QueuePtr rear; }LinkQueue; Status InitQueue(LinkQueue *Q) { Q->front=Q->rear=(QueuePtr)malloc(sizeof(QNode)); if(!Q->front)exit(-1); Q->front->next=NULL; return 1; } Status EnQueue(LinkQueue *Q,int e) { QueuePtr p; p=(QueuePtr)malloc(sizeof(QNode)); if(!p)exit(-1); p->data=e;p->next=NULL; Q->rear->next=p; Q->rear=p; return 1; } Status QueueEmpty(LinkQueue *Q) { if(Q->front==Q->rear) return 1; else return 0; } Status DeQueue(LinkQueue *Q) { QueuePtr p; if(Q->front==Q->rear)return 0; p=Q->front->next; top=p->data; Q->front->next=p->next; if(Q->rear==p)Q->rear=Q->front; free(p); return 1; } int visiT(int v) { if(v==k) flag=1; return 1; } void BFSTraverse(MGraph *G,Status(*Visit)(int v)) { int v,w; LinkQueue Q; InitQueue(&Q); v=n; if(!visited[v]) { visited[v]=1; Visit(v); EnQueue(&Q,v); while(!QueueEmpty(&Q)&&flag==0) { DeQueue(&Q); w=top; if(w<=100000) { if(!visited[w+1]) { visited[w+1]=1; step[w+1]=step[w]+1; Visit(w+1); EnQueue(&Q,w+1); } if(!visited[w-1]) { visited[w-1]=1; step[w-1]=step[w]+1; Visit(w-1); EnQueue(&Q,w-1); } if(!visited[w*2]) { visited[w*2]=1; step[w*2]=step[w]+1; Visit(w*2); EnQueue(&Q,w*2); } } } } } int main() { MGraph G; flag=0; memset(visited,0,sizeof(visited)); memset(step,0,sizeof(step)); scanf("%d%d",&n,&k); BFSTraverse(&G,visiT); printf("%d\n",step[k]); return 0; }
