标签:des style http color io os ar for strong
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3152


3 5 5 4 3 9 1 3 2 7 5 3 7 2 0 1 2 8 0 9 1 1 2 1 8 1 9 8 9 2 0 3 6 5 1 5 7 9 0 5 1 1 5 3 4 1 2 1 6 5 3 0 7 6 1 6 8 5 1 1 7 8 3 2 3 9 4 0 7 6 4 1 5 8 3 2 4 8 3 7 4 8 4 8 3 4 0
Problem 1: 20 Problem 2: 19 Problem 3: 36
题意:
从左上到右下的路径中,寻找一条经过的格子中的数字之和最小的路径。
移动方向可以上、下、左、右。
PS:
由于以前做过HDU2084,所以第一感觉是用DP来做,但是此题可以再走已经走过的点,
所以只有用记忆化搜索!
优先队列优化!
代码如下:
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
const int maxn = 177;
struct node
{
int x, y;
int dis;
bool operator<(const node &s)const
{
return dis > s.dis;
}
};
int n;
int mm[maxn][maxn];
int vis[maxn][maxn];
int dx[4] = {1,0,-1,0};
int dy[4] = {0,-1,0,1};
int BFS(int dis)
{
priority_queue<node> q;
node fro, pre;
fro.x = 0, fro.y = 0;
fro.dis = dis;
q.push(fro);
while(!q.empty())
{
fro = q.top();
q.pop();
for(int i = 0; i < 4; i++)
{
int xx = fro.x+dx[i];
int yy = fro.y+dy[i];
if(xx>=0&&xx<n&&yy>=0&&yy<n)
{
pre.x = xx, pre.y = yy;
pre.dis = fro.dis + mm[xx][yy];
if(vis[xx][yy]==-1||vis[xx][yy]>pre.dis)
{
//没有访问过,或者当前的不是最短的
vis[xx][yy] = pre.dis;
if(xx!=n-1 || yy!=n-1)
q.push(pre);
}
}
}
}
return vis[n-1][n-1];
}
int main()
{
int cas = 0;
while(scanf("%d",&n)&&n)
{
memset(vis,-1,sizeof(vis));
for(int i = 0; i < n; i++)
{
for(int j = 0; j < n; j++)
{
scanf("%d",&mm[i][j]);
}
}
int ans = BFS(mm[0][0]);
printf("Problem %d: %d\n",++cas,ans);
}
return 0;
}
HDU 3152 Obstacle Course(BFS+优先队列 重载)
标签:des style http color io os ar for strong
原文地址:http://blog.csdn.net/u012860063/article/details/39859083