算法——Coin-collecting by robot(硬幣收集問題)

題目描述

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.

輸入

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.

輸出

The max number Coin-collecting by robot.

樣例輸入

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

樣例輸出

5

代碼

#include<iostream>
using namespace std;
int Coor[1000][1000];
int main(){
	int N, M;
	cin>>N>>M;
	for(int i = 1; i <= N; i++){
		for(int j = 1; j <= M; j++){
			cin>>Coor[i][j];
			if(i == 1 && j > 1) Coor[1][j] += Coor[1][j-1];
			if(j == 1 && i > 1) Coor[i][1] += Coor[i-1][1];
			if(i > 1 && j > 1) Coor[i][j] += max(Coor[i][j-1],Coor[i-1][j]);
		}
	}  
	cout<<Coor[N][M]<<endl;
	return 0;
}

思路

  1. 動態規劃問題;

  2. 令F( i , j )爲機器人截止到第 i 行第 j 列單元格 ( i , j ) 能夠收集到的最大硬幣數, 有如下遞推式:
    在這裏插入圖片描述

  3. 值得注意的是:遞歸算法解題相對常用的算法如普通循環等,運行效率較低。因此,應該儘量避免使用遞歸,除非沒有更好的算法或者某種特定情況,遞歸更爲適合的時候。在遞歸調用的過程當中系統爲每一層的返回點、局部量等開闢了棧來存儲。遞歸次數過多容易造成棧溢出等。

  4. 我第一次用了遞歸的方式,出現了 Time Limit Exceeded ,普通循環修正以後,便可以通過。

  5. 但可以 利用上面的公式,我們可以通過逐行或者逐列的方式填充 n 乘以 m 表以求得F( i , j )。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章