P1005 矩阵取数游戏
简单的dp题,关键是数太大,需要自己写高精度。
ps:大数写错了,有几组数据报错,回头看一个标准答案学一下,太菜了。
#include<iostream>
#include<algorithm>
#include <cstring>
using namespace std;
#define ll long long
const int MAX = 100;
ll a[MAX];
int n, m;
struct big {
ll n[MAX] = { 0 };
int l = 0;
}dp[MAX][MAX], ans[MAX], bit[MAX], all[MAX];
void crebig(ll a, big &b)
{
if (!a) { b.n[0] = 0; b.l = 1; return; }
b.l = 0;
while (a)
{
b.n[b.l] = a % 10;
a /= 10;
b.l++;
}
}
void rebig(big &a)
{
a.l = 0;
int l = 0;
while (l<MAX-1) {
a.n[l + 1] += a.n[l] / 10;
a.n[l] %= 10;
l++;
if (a.n[l])a.l = l+1;
}
if (a.l == 0)a.l = 1;
}
void coutbig(big a)
{
for (int i = a.l-1; i >=0; i--)
cout << a.n[i];
cout << endl;
}
void bigmax(big a, big b,big &c)
{
if (a.l > b.l) { c = a; return; }
else if (a.l < b.l) { c = b; return; }
else {
for (int i = a.l; i >= 0; i--) {
if (a.n[i] > b.n[i]) { c = a; return; }
if (a.n[i] < b.n[i]) { c = b; return; }
}
}
}
void bigadd(big a, big b, big &c)
{
memset(c.n, 0, sizeof(c.n));
for (int i = 0; i < max(a.l, b.l); i++)
{
c.n[i] = a.n[i] + b.n[i];
}
rebig(c);
}
void bigmul(ll a, big b, big &c)
{
memset(c.n, 0, sizeof(c.n));
for (int i = 0; i < b.l; i++)
{
c.n[i] = a * b.n[i];
}
rebig(c);
}
void crebit()
{
bit[0].l = 1;
bit[0].n[0] = 1;
for (int i = 1; i < MAX; i++)
{
bigmul(2, bit[i - 1], bit[i]);
}
}
int main()
{
cin >> n >> m;
big temp, add;
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= m; j++)
cin >> a[j];
memset(dp, 0, sizeof(dp));
crebit();
for (int j = 1; j <= m; j++)
bigmul(a[j], bit[m], dp[j][j]);
for (int k = 1; k <= m - 1; k++)
{
for (int j = 1; j <= m - k; j++)
{
bigmul(a[j + k], bit[m - k], temp);
bigadd(dp[j][j + k - 1], temp, add);
bigmax(dp[j][j + k], add, dp[j][j + k]);
bigmul(a[j], bit[m - k], temp);
bigadd(dp[j + 1][j + k], temp, add);
bigmax(dp[j][j + k], add, dp[j][j + k]);
//dp[j][j + k] = max(dp[j][j + k - 1] + a[j + k] * bit, dp[j + 1][j + k] + a[j] * bit);
}
}
ans[i] = dp[1][m];
}
all[0].l = 1;
all[0].n[0] = 0;
for (int i = 1; i <= n; i++)
bigadd(ans[i], all[i-1], all[i]);
coutbig(all[n]);
return 0;
}