Time limit(ms): 1000 Memory limit(kb): 65535
Several coins are placed in cells of an n×m board. A robot, located in the upper left cell of the board, needs to collect as many of the coins as possible and bring them to the bottom right cell. On each step, the robot can move either one cell to the right or one cell down from its current location.
Description
The fist line is n,m, which 1< = n,m <= 1000.
Then, have n row and m col, which has a coin in cell, the cell number is 1, otherwise is 0.
Then, have n row and m col, which has a coin in cell, the cell number is 1, otherwise is 0.
Input
The max number Coin-collecting by robot.
Output
1
2
3
4
5
6
7
|
5 6
0 0 0 0 1 0
0 1 0 1 0 0
0 0 0 1 0 1
0 0 1 0 0 1
1 0 0 0 1 0
|
Sample Input
1
2
|
5
|
Sample Output
Hint
algorithm text book
题目大意:就是给出一个方阵nXm,每个格子1代表有硬币,0代表没有,问从左上角,到右下角(每次只能向下和向右移动)最多能收集多少硬币
思路其实也挺简单的就是一个从终点到起点的反向dp,每次只能每次只能向下和向右移动(注意dp是反向进行的)
于是得到了一个dp方程dp[i][j] += max(dp[i + 1][j] , dp[i][j + 1] ) 注:这里为了降低空间复杂度直接用dp数据存贮的矩阵
代码如下
#include <stdio.h>
int rows, dp[][];
int main()
{
int i, j, n, m;
scanf("%d%d", &n, &m);
for (i = ; i < n; i++)
for (j = ; j < m; j++)
scanf("%d", &dp[i][j]);
for (i = n - ; i >= ; i--)
for (j = m - ; j >= ; j--)
dp[i][j] += dp[i + ][j] > dp[i][j + ] ? dp[i + ][j] : dp[i][j + ];
printf("%d\r\n", dp[][]);
return ;
}
其实最开始并没有想到dp(还是题做的少,没这个概念),直接两个方位的bfs+优先队列
感觉应该是对的,为啥就是wa 呢?贴出代码,求大神指教
#include <iostream>
#include <queue>
#include <algorithm>
using namespace std;
int map[][], vis[][], dir[][] = { , , , };
int n, m;
struct node{
int x, y, cur;
friend bool operator<(node x, node y){
return x.cur < y.cur;
}
};
int bfs(){
priority_queue<node>Q;
struct node now, next;
now.x = now.y = , now.cur = map[][];
vis[][] = ;
Q.push(now);
while (!Q.empty()){
now = Q.top();
Q.pop();
if (now.x == n&&now.y == m)
return now.cur;
for (int i = ; i < ; i++){
next.x = now.x + dir[i][];
next.y = now.y + dir[i][];
if (next.x >= && next.x <= n && next.y >= && next.y <= m &&!vis[next.x][next.y]){
next.cur = now.cur + map[next.x][next.y];
vis[next.x][next.y] = ;
Q.push(next);
}
}
}
}
int main(){
cin >> n >> m;
for (int i = ; i <= n; i++)
for (int j = ; j <= m; j++)
cin >> map[i][j];
cout << bfs() << "\r\n";
return ;
}