Sicily 1158 Pick numbers

Constraints

Time Limit: 1 secs, Memory Limit: 32 MB

Description

Given a matrix of size M*N, the elements of which are integer numbers from -10 to 10. You task is to go from the top-left corner (1, 1) to the bottom-right corner (M, N). You can only move right or down, and you can not go out of the matrix. The number in the grid you passed must be picked. The sum of numbers you picked must be positive and as minimal as possible.

Input

The input contains several test cases.

      The first line of each test case are two integer numbers M, N (2<=M<=10, 2<=N<=10), indicating the number of rows and columns of the matrix. The following M lines, each contains N integer numbers.

Output

For each test case, output the sum of numbers you picked on a single line. If you can't get a positive sum, output -1.

Sample Input

2 2
0 2
1 0

3 3
0 0 0
0 0 0
0 0 0

Sample Output

1
-1

Problem Source

ZSUACM Team Member


Solution

给出m*n的矩阵,找出一条路从左上到右下,方向只有向右或者向下,求路的最小正权值。

我一开始想到的是dp,状态转移方程:dp(i,j)=min(dp(i-1,j), dp(i, j+1))+data[i][j]。但是要求的是最小正权值,可能存在的情况是虽然最小权值是负的,但是有正权值的答案。

这时候dp的方法就是有漏洞的。

然后就直接穷举所有路了,BFS。


#include <iostream>
#include <algorithm>
#include <queue>

using namespace std;

struct Point
{
  int x, y, sum;
  Point() {}
  Point(int i, int j, int k) : x(i), y(j), sum(k) {}
}temp;
int data[15][15];

int main()
{
  int i, j, m, n;

  while (cin >> m >> n)
  {
    for (i = 0; i < m; ++i)
      for (j = 0; j < n; ++j) cin >> data[i][j];

    int ans = 1e9;//预设的答案
    queue<Point> q;
    q.push(Point(0, 0, data[0][0]));
    while (!q.empty())
    {
      temp = q.front();
      q.pop();

      if (temp.x == m-1 && temp.y == n-1 && temp.sum > 0)
        ans = min(temp.sum, ans);
      if (temp.x + 1 < m) q.push(Point(temp.x+1, temp.y, temp.sum+data[temp.x+1][temp.y]));//right
      if (temp.y + 1 < n) q.push(Point(temp.x, temp.y+1, temp.sum+data[temp.x][temp.y+1]));//down
    }

    if (ans != 1e9) cout << ans << endl;
    else cout << -1 << endl;
  }

  return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值