hdu 4308 Saving Princess claire_(BFS)

来源:互联网 发布:淘宝网扇子舞视频 编辑:程序博客网 时间:2024/05/21 18:47

这道题主要有两个问题。

一、解决内存大小的问题,这道题需要动态申请内存,如果直接开一个5000*5000的内存,会MLE。

二、题目数据有问题,我记录的cost用int提交wa,改为long long提交之后AC。但是题目保证最多5000个节点,每个节点的花费不超过10000,理论上最大花费是5*10^7,不会超int。

#include<stdio.h>#include<string.h>#include<stdlib.h>#include<queue>using namespace std;#define N 5005typedef long long LL;int n,m,k,cnt;int **mark,**vis;int dir[4][2]={{1,0},{0,1},{-1,0},{0,-1}};int sx,sy;char s[N];struct node{    int x,y;    LL cost;    friend bool operator<(node a,node b)    {        return a.cost>b.cost;    };};struct point{    int x,y;}hash[N];int judge(int x,int y){    if(x<1||x>m||y<1||y>n) return 0;    if(vis[x][y]==1) return 0;    if(mark[x][y]==-1) return 0;    return 1;}LL BFS(){    node cur,next;    priority_queue<node>q;    cur.x=sx;cur.y=sy;cur.cost=0;    vis[cur.x][cur.y]=1;    q.push(cur);    while(!q.empty())    {       cur=q.top();       q.pop();       for(int i=0;i<4;i++)       {           next.cost=cur.cost;           next.x=cur.x+dir[i][0];           next.y=cur.y+dir[i][1];           if(judge(next.x,next.y))           {               if(mark[next.x][next.y]==1) next.cost=cur.cost+k;               vis[next.x][next.y]=1;               if(mark[next.x][next.y]==2) return next.cost;               q.push(next);           }       }       if(mark[cur.x][cur.y]==10)       {           for(int i=0;i<cnt;i++)           {               next.x=hash[i].x;               next.y=hash[i].y;               next.cost=cur.cost;               if(judge(hash[i].x,hash[i].y))               {                   vis[hash[i].x][hash[i].y]=1;                   q.push(next);               }           }       }    }    return -1;}int main(){    while(scanf("%d%d%d",&m,&n,&k)!=EOF)    {        getchar();        mark=(int **)malloc((m+2)*sizeof(int *));        for(int i=0;i<=m+1;i++) mark[i]=(int *)malloc((n+2)*sizeof(int));        vis=(int **)malloc((m+2)*sizeof(int *));        for(int i=0;i<=m+1;i++) vis[i]=(int *)malloc((n+2)*sizeof(int));        cnt=0;        for(int i=1;i<=m;i++)        {            gets(s+1);            for(int j=1;j<=n;j++)            {                if(s[j]=='Y')                {                    mark[i][j]=0;                    sx=i;                    sy=j;                }                else if(s[j]=='C') mark[i][j]=2;                else if(s[j]=='#') mark[i][j]=-1;                else if(s[j]=='*') mark[i][j]=1;                else if(s[j]=='P')                {                    mark[i][j]=10;                    hash[cnt].x=i;hash[cnt].y=j;cnt++;                }            }        }        LL ans;        memset(vis,0,sizeof(vis));        ans=BFS();        if(ans==-1) printf("Damn teoy!\n");        else printf("%I64d\n",ans);    }    return 0;}


原创粉丝点击