题目
用优先队列优化普通的广搜就可以过了。
#include<stdio.h>#include<string.h>#include<algorithm>using namespace std;#include<queue>struct pq{ int x,y,val; friend bool operator < (pq a,pq b) { return a.val > b.val; }};priority_queue <pq> q;int xx[4]={0,0,1,-1};int yy[4]={1,-1,0,0};int n;int mp[130][130],vis[130][130];int i,j,k;int bfs(int x,int y){ if(x==n-1&&y==n-1)return mp[x][y]; while(!q.empty())q.pop(); memset(vis,0,sizeof(vis)); pq topp; topp.x=x;topp.y=y;topp.val=mp[x][y]; q.push(topp); vis[x][y]=1; while(!q.empty()) { pq tmp=q.top(); q.pop(); vis[tmp.x][tmp.y]=1; for(i=0;i<4;i++) { pq nxt; nxt.x=tmp.x+xx[i]; nxt.y=tmp.y+yy[i]; nxt.val=tmp.val+mp[nxt.x][nxt.y]; if(vis[nxt.x][nxt.y]==0&&nxt.x>=0&&nxt.y>=0&&nxt.x<n&&nxt.y<n){ if(nxt.x==n-1&&nxt.y==n-1)return nxt.val; q.push(nxt); } } }}int main(){ int id=1; while(scanf("%d",&n),n) { for(i=0;i<n;i++) { for(j=0;j<n;j++){ scanf("%d",&mp[i][j]); } } printf("Problem %d: %d\n",id++,bfs(0,0)); } system("pause"); return 0;}
View Code
HDU 3152 Obstacle Course(优先队列,广搜)