您的位置:首页 > 其它

sicily 1158. Pick numbers bfs

2011-04-15 18:29 435 查看
//这题一开始感觉是dp,状态转移方程为dp[i][j] = min(dp[i][j-1], dp[i-1][j]) + maze[i][j]
//提交上去WA
//后来发现这题不能用dp,因为题目要求的是正的最小值,状态转移方程的min会取到负数,
//当求出dp
[m]为负数时,有可能存在一条和为正的路径
//注意到n,m都比较小,可以直接用bfs搜索过
#include <iostream>
#include <queue>
using namespace std;

const int N = 15;
const int INF = 1000000000;

int maze

;
int n, m;
int ans;
int dx[] = {1, 0};
int dy[] = {0, 1};

struct status
{
int row,col,sum;
status() {}
status (int row, int col, int sum)
{
this->row = row;
this->col = col;
this->sum = sum;
}
};

void bfs()
{
queue<status> Q;
Q.push(status(1, 1, maze[1][1]));
status p,tmp;

while (!Q.empty())
{
p = Q.front();
Q.pop();
if (p.row == n && p.col == m && p.sum > 0)
ans = min(p.sum, ans);

for (int i = 0; i < 2; i++)
{
tmp = p;
tmp.row += dx[i];
tmp.col += dy[i];
if (tmp.row >= 1 && tmp.row <= n && tmp.col >= 1 && tmp.col <= m)
{
tmp.sum += maze[tmp.row][tmp.col];
Q.push(tmp);
}
}
}
}

int main()
{
while (cin >> n >> m)
{
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
cin >> maze[i][j];

ans = INF;
bfs();
if (ans < INF)
cout << ans << endl;
else
cout << -1 << endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: