nyoj 171 能不能用优先队列

wang19980123 2017-08-03 05:38:31
这是一道动态规划的题,可是我写了优先队列答案对了输出的是错误答案,我想知道动态规划的题难道不能用搜索吗

#include<stdio.h>
#include<string.h>
#include<queue>
#include<algorithm>
using namespace std;
int n,m,mp[100][100],book[100][100];
int next[2][2]= {{1,0},{0,1}};
struct note
{
int x,y,sum;
bool operator <(const note &a) const
{
return a.sum>sum;
}
};
void bfs(int x,int y)
{
priority_queue<note>q;
note now,temp;
now.x=x;
now.y=y;
now.sum=mp[x][y];
q.push(now);
book[x][y]=1;
int tx,ty;
while(!q.empty())
{
now=q.top();
q.pop();
if(now.x==n-1&&now.y==m-1)
{
printf("%d\n",now.sum);
break;
}
for(int i=0; i<2; i++)
{
tx=now.x+next[i][0];
ty=now.y+next[i][1];
if(tx<0||ty<0||tx>=n||ty>=m||book[tx][ty])continue;
temp.sum=now.sum+mp[tx][ty];
temp.x=tx;
temp.y=ty;
book[tx][ty]=1;
q.push(temp);
}
}
}
int main()
{
int i,j;
while(~scanf("%d%d",&n,&m))
{
for(i=0; i<n; i++)
for(j=0; j<m; j++)
scanf("%d",&mp[i][j]);
memset(book,0,sizeof(book));
book[0][0]=1;
bfs(0,0);
}
return 0;
}
...全文
104 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

69,371

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧