2015年湖南省省赛E题 简单的图论问题 CSU1780

来源:互联网 发布:知乎 闲书 编辑:程序博客网 时间:2024/05/17 18:48

题意很简单,写两个优先队列的bfs即可,dis小的排在前面即可,第二个bfs开一个变量记录每次从当前位置转移到下一个位置的方向即可。


#include<iostream>#include<cstdio>#include<cstring>#include<queue>#define INF 0x3f3f3f3fusing 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;}


0 1
原创粉丝点击