题意:n*m(n, m<=80)的矩阵,每次从各行首或尾取一个数,获得分值Sigma 数值*2^i,i是取数次数,从1算起。
决策:从行首或行尾取一个数。各行之间独立,每行单独考虑,可以用DP解决。
整个程序DP就几行,高精度代码占主要篇幅……其实我是为了测试刚写的高精度类才写这题。
用了高精度乘法。看了其他解答,发现没必要,因为2*2=2+2。
第一次忘删调试语句,0分。第二次由于高精度类初始化把base
写成10
,只有10分。高精度类一定要先检查无误再使用。
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long ll;
const int MAX_M = 80;
int n, m;
struct Big {static const int w = 4, base = 1e9, lg = 9;int x[w];Big(int a=0){*this = a;}Big operator=(int a){for (int i = 0; i < w; ++i, a /= base)x[i] = a % base;return *this;}Big operator+(const Big& b) const{Big c;int flag = 0;for (int i = 0; i < w; ++i)if (flag = (c.x[i] = x[i] + b.x[i] + flag) >= base)c.x[i] -= base;return c;}Big operator*(const Big& b) const{Big c;for (int i = 0; i < w; ++i) {int flag = 0;for (int j = 0; i+j < w; ++j) {ll t = (ll)x[j]*b.x[i] + c.x[i+j] + flag;c.x[i+j] = t % base;flag = t / base;}}return c;}bool operator<(const Big& b) const{for (int i = w-1; i >= 0; --i)if (x[i] != b.x[i])return x[i] < b.x[i];return false;}void print() const{int i = w-1;while (i && !x[i])--i;printf("%d", x[i--]);while (i >= 0)printf("%0*d", lg, x[i--]);}} a[MAX_M], f[MAX_M][MAX_M], w[MAX_M+1], ans;
bool b[MAX_M][MAX_M];Big dp(int i, int j, int k)
{if (b[i][j])return f[i][j];b[i][j] = true;return f[i][j] = i == j ? a[i]*w[k] : max(dp(i+1, j, k+1) + a[i]*w[k], dp(i, j-1, k+1) + a[j]*w[k]);
}int main()
{scanf("%d %d", &n, &m);w[0] = 1;for (int i = 1; i <= m; ++i)w[i] = Big(2)*w[i-1];for (int i = 0; i < n; ++i) {for (int j = 0; j < m; ++j) {int c;scanf("%d", &c);a[j] = c;}memset(b, 0, sizeof(b));ans = ans + dp(0, m-1, 1);}ans.print();return 0;
}