标签:
原题链接:http://acm.hunnu.edu.cn/online/?action=problem&type=show&id=11657&courseid=0
正如好手所说,搜索玩得就是标记
第一种方式稍微简单一点,第二种方式需要一个三维的标记,增加一个方向的标记,就和迷宫问题转弯次数一样。
#include <iostream> #include <cstdio> #include <cstring> #include <cstdlib> #include <queue> using namespace std; int a[505][505]; bool vis1[505][505]; bool vis2[505][505][4]; int n,m,sx,sy,ex,ey; struct node { int x,y,sum; int dir; bool friend operator <(node a,node b) { return a.sum>b.sum; } }; int dir[4][2]= {1,0,0,1,-1,0,0,-1}; bool OK(int x,int y) { if(x<1||x>n||y<1||y>m) return false; return a[x][y]!=0; } int BFS1() { priority_queue<node>q; node now,nextt; now.x=sx; now.y=sy; now.sum=a[sx][sy]; q.push(now); memset(vis1,false,sizeof(vis1)); vis1[sx][sy]=true; while(!q.empty()) { now=q.top(); q.pop(); if(now.x==ex&&now.y==ey) return now.sum; for(int i=0; i<4; i++) { nextt.x=now.x+dir[i][0]; nextt.y=now.y+dir[i][1]; if(OK(nextt.x,nextt.y)&&!vis1[nextt.x][nextt.y]) { vis1[nextt.x][nextt.y]=true; nextt.sum=now.sum+a[nextt.x][nextt.y]; q.push(nextt); } } } return -1; } int BFS2() { priority_queue<node>q; node now,nextt; now.x=sx; now.y=sy; now.sum=a[sx][sy]; now.dir=-1; q.push(now); memset(vis2,false,sizeof(vis2)); vis2[sx][sy][0]=true; vis2[sx][sy][1]=true; vis2[sx][sy][2]=true; vis2[sx][sy][3]=true; while(!q.empty()) { now=q.top(); q.pop(); if(now.x==ex&&now.y==ey) return now.sum; for(int i=0; i<4; i++) { nextt.x=now.x+dir[i][0]; nextt.y=now.y+dir[i][1]; if(now.dir==i) continue; if(OK(nextt.x,nextt.y)&&!vis2[nextt.x][nextt.y][i]) { vis2[nextt.x][nextt.y][i]=true; nextt.sum=now.sum+a[nextt.x][nextt.y]; nextt.dir=i; q.push(nextt); } } } return -1; } int main() { //freopen("e.txt","r",stdin); int kase=0; while(cin>>n>>m>>sx>>sy>>ex>>ey) { char ch[10]; for(int i=1; i<=n; i++) { for(int j=1; j<=m; j++) { scanf("%s",ch); if(!strcmp(ch,"*")) a[i][j]=0; else a[i][j]=atoi(ch); } } printf("Case %d: ",++kase); cout<<BFS1()<<" "<<BFS2()<<endl; } return 0; } /** 2 4 1 1 1 4 1 * 3 4 9 9 * 9 4 4 1 2 3 2 7 10 3 9 * 45 6 2 * 8 14 * 21 1 * * 2 4 1 1 1 4 1 2 3 4 9 * * 9 2 4 1 1 1 4 1 * 3 4 9 9 * 9 */
HNNU 11657 简单的图论问题?【湖南省第十一届大学生计算机程序设计竞赛,双BFS】
标签:
原文地址:http://blog.csdn.net/hurmishine/article/details/52292110