2015年湖南省省賽E題 簡單的圖論問題 CSU1780

題意很簡單,寫兩個優先隊列的bfs即可,dis小的排在前面即可,第二個bfs開一個變量記錄每次從當前位置轉移到下一個位置的方向即可。


#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
#define INF 0x3f3f3f3f
using namespace std;
const int maxn=512;
int n,m,sx,sy,ex,ey;
int a[maxn][maxn],vis[maxn][maxn],vvis[maxn][maxn][4];
char s[4];
int dx[4]={0,+1,0,-1};
int dy[4]={+1,0,-1,0};

struct node
{
    int x,y,dis,go;
    node(){}
    node(int a,int b,int c){x=a;y=b;dis=c;}
    bool operator< (const node&p)const
    {
        return dis>p.dis;
    }
};

int get(char *s)
{
    int len=strlen(s);
    int res=0;
    for(int i=0;i<len;i++)
    {
        res=res*10+s[i]-'0';
    }
    return res;
}

int bfs1()
{
    memset(vis,0,sizeof vis);
    priority_queue<node> qq;
    node st(sx,sy,a[sx][sy]),now;
    qq.push(st);
    vis[st.x][st.y]=1;
    while(!qq.empty())
    {
        node tmp=qq.top();
        int px=tmp.x,py=tmp.y,pdis=tmp.dis;
        qq.pop();
        for(int i=0;i<4;i++)
        {
            now.x=px+dx[i];
            now.y=py+dy[i];
            now.dis=pdis+a[now.x][now.y];
            if(a[now.x][now.y]==-1||now.x<=0||now.x>n||now.y<=0||now.y>m) continue;
            if(!vis[now.x][now.y])
            {
                if(now.x==ex&&now.y==ey) return now.dis;
                qq.push(now);
                vis[now.x][now.y]=1;
            }
        }
    }
    return -1;
}

int bfs2()
{
    memset(vvis,0,sizeof vvis);
    priority_queue<node> qq;
    node st(sx,sy,a[sx][sy]),now;
    qq.push(st);
    while(!qq.empty())
    {
        node tmp=qq.top();
        int px=tmp.x,py=tmp.y,pdis=tmp.dis;
        qq.pop();
        for(int i=0;i<4;i++)
        {
            now.x=px+dx[i];
            now.y=py+dy[i];
            now.dis=pdis+a[now.x][now.y];
            now.go=i;
            if(a[now.x][now.y]==-1||now.x<=0||now.x>n||now.y<=0||now.y>m) continue;
            if(!vvis[now.x][now.y][i]&&i!=tmp.go)
            {
                if(now.x==ex&&now.y==ey) return now.dis;
                qq.push(now);
                vvis[now.x][now.y][i]=1;
            }
        }
    }
    return -1;
}

int main()
{
    int cas=0;
    //freopen("in.txt","r",stdin);
    //freopen("out.txt","w",stdout);
    while(~scanf("%d%d%d%d%d%d",&n,&m,&sx,&sy,&ex,&ey))
    {
        for(int i=1;i<=n;i++)
        {
            for(int j=1;j<=m;j++)
            {
                scanf("%s",s);
                if(s[0]=='*') a[i][j]=-1;
                else a[i][j]=get(s);
            }
        }
        printf("Case %d: ",++cas);
        printf("%d %d\n",bfs1(),bfs2());
    }
    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章