思路和AC代码:
#include <bits/stdc++.h>
#define IN \
ios::sync_with_stdio(0); \
cin.tie(0);
using namespace std;
#define ll long long
const int N = 1e2 + 10;
int n, m;
int a[N][N];
int ans[N]; // 存储答案
int f[N][N]; // f[i][j]表示前i种花已经放置到位置j时的最大价值
int main() {
cin >> n >> m;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
cin >> a[i][j];
}
}
memset(f, 0xcf, sizeof(f));
for (int i = 0; i <= m; i++) {
f[0][i] = 0; // 不放花时所有位置最大价值为0
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
if (j < i)
continue;
// 在位置j处不放花;在位置j处放花
f[i][j] = max(f[i][j - 1], f[i - 1][j - 1] + a[i][j]);
}
}
// 这一步回溯很巧妙
for (int i = n, j = m; i; ans[i--] = j--) {
while (f[i][j] == f[i][j - 1])
j--;
}
cout << f[n][m] << endl;
for (int i = 1; i <= n; i++) {
cout << ans[i] << " ";
}
return 0;
}