Top k path--動態規劃
Description
A robot is located at the top-left corner of a m×nm×n grid. The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid. There is a non-negative integer in each small grid which means the score that the robot get when it passes this grid. Now you need to calculate the top kk
Note: The top k total scores may contain same total score got from different paths.
Input
The first line of input are m and n,which denote the size of the grid. The second line of input is the kk. The next m lines are the score matrix. (1≤m,n,k≤1001≤m,n,k≤100,and 0≤score≤1000≤score≤100)
Output
There is only one line in the Output,which is a descending sequence consist of the top k total scores.
Sample1
Input
3 3
2
3 2 5
3 2 2
4 2 1
Output
13 13
Sample2
Input
4 3
3
7 1 5
4 6 2
4 2 1
5 7 3
Output
30 29 27
#include <iostream> using namespace std; const int maxn = 200; int m, n, K;//矩陣m*n,輸出TOPK的值 int dp[maxn][maxn][maxn]; int a[maxn][maxn]; void solve() { dp[1][1][1] = a[1][1]; for (int k = 2; k <= K; k++) dp[1][1][k] = -1; for (int j = 2; j <= n; j++) { dp[1][j][1] = dp[1][j - 1][1] + a[1][j]; for (int k = 2; k <= K; k++) dp[1][j][k] = -1; } for (int i = 2; i <= m; i++) { for (int k = 1; k <= K; k++) { if (~dp[i - 1][1][k]) dp[i][1][k] = a[i][1] + dp[i - 1][1][k]; else dp[i][1][k] = -1; } for (int j = 2; j <= n; j++) { int ple = 1, pri = 1; int nex = 1; while (nex <= K) { int & x = dp[i - 1][j][ple]; int & y = dp[i][j - 1][pri]; if (x == -1 && y == -1) { dp[i][j][nex++] = -1; continue; } if (x >= y) { dp[i][j][nex++] = x + a[i][j]; ple++; } else { dp[i][j][nex++] = y + a[i][j]; pri++; } } } } } int main() { cin >> m >> n >> K; for (int i = 1; i <= m; i++) { for (int j = 1; j <= n; j++) { cin >> a[i][j]; } } solve(); for (int k = 1; k <= K; k++) { cout << dp[m][n][k] << (k == K ? '\n' : ' ');//控制輸出格式 } return 0; }