tractor 拖拉机

来源:互联网 发布:养宠物猪 知乎 编辑:程序博客网 时间:2024/04/20 08:31
#include<stdio.h>#include<iostream>#include<queue>#include<memory.h>using namespace std;const int MAX_M = 1002;int dx[]={0,0,1,-1};int dy[]={1,-1,0,0};bool G[MAX_M][MAX_M];bool used[MAX_M][MAX_M];int f[MAX_M][MAX_M];int N;struct node{       int x,y;       int c;}head,next;bool operator<(struct node a,struct node b){     return a.c>=b.c;}priority_queue<struct node> Q;int Sx,Sy;int Tx,Ty;int ans;void init(){     int i,j;     int x,y;     memset(G,false,sizeof(G));     memset(f,1,sizeof(f));     memset(used,true,sizeof(used));     Tx=Ty=0;     scanf("%d %d %d",&N,&Sx,&Sy);     for(i=1;i<=N;i++)     {         scanf("%d %d",&x,&y);         G[x][y]=true;     }     f[Sx][Sy]=0;     head.x=Sx;     head.y=Sy;     head.c=0;     Q.push(head);}void work(){     while (!Q.empty())     {           head=Q.top();           Q.pop();           if (head.x==Tx&&head.y==Ty)            {                ans=head.c;                break;           }           if(used[head.x][head.y])           {                used[head.x][head.y]=false;                int i;                for (i=0;i<4;i++)                {                    next.x=head.x+dx[i];                    next.y=head.y+dy[i];                    if (next.x>=0&&next.x<MAX_M&&next.y>=0&&next.y<MAX_M&&used[next.x][next.y])                    {                          next.c=head.c+G[next.x][next.y];                          if (next.c<f[next.x][next.y])                          {                               f[next.x][next.y]=next.c;                               Q.push(next);                          }                    }                }           }     }}void put(){     printf("%d",ans);}int main(){    freopen("tractor.in","r",stdin);    freopen("tractor.out","w",stdout);    init();    work();    put();    return 0;}


老师讲过的,不重复。

 

原创粉丝点击