线性DP,使用单调队列优化。
/* 4374 */
#include <iostream>
#include <sstream>
#include <string>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <vector>
#include <deque>
#include <algorithm>
#include <cstdio>
#include <cmath>
#include <ctime>
#include <cstring>
#include <climits>
#include <cctype>
#include <cassert>
#include <functional>
#include <iterator>
#include <iomanip>
using namespace std;
//#pragma comment(linker,"/STACK:102400000,1024000") #define sti set<int>
#define stpii set<pair<int, int> >
#define mpii map<int,int>
#define vi vector<int>
#define pii pair<int,int>
#define vpii vector<pair<int,int> >
#define rep(i, a, n) for (int i=a;i<n;++i)
#define per(i, a, n) for (int i=n-1;i>=a;--i)
#define clr clear
#define pb push_back
#define mp make_pair
#define fir first
#define sec second
#define all(x) (x).begin(),(x).end()
#define SZ(x) ((int)(x).size())
#define lson l, mid, rt<<1
#define rson mid+1, r, rt<<1|1 const int INF = 0x3f3f3f3f;
const int maxn = ;
const int maxm = ;
int n, m, x, t;
int score[maxn][maxm];
int dp[maxn][maxm];
int P[maxm], Q[maxm];
int sum[maxm]; void solve() {
int i, j, k;
int lpos, rpos;
int l, r, tmp; for (i=; i<=n; ++i)
for (j=; j<=m; ++j)
dp[i][j] = -INF; for (j=; j<=m; ++j)
sum[j] = sum[j-] + score[][j];
for (lpos=max(,x-t),j=lpos; j<=x; ++j)
dp[][j] = sum[x] - sum[j-];
for (rpos=min(m,x+t),j=rpos; j>x; --j)
dp[][j] = sum[j] - sum[x-]; for (i=; i<=n; ++i) {
for (j=; j<=m; ++j)
sum[j] = sum[j-] + score[i][j]; // k <= j
l = , r =;
for (j=; j<=m; ++j) {
lpos = max(, j-t);
tmp = dp[i-][j] - sum[j-];
while (l<=r && Q[r]<=tmp)
--r;
Q[++r] = tmp;
P[r] = j;
while (P[l] < lpos)
++l;
dp[i][j] = max(dp[i][j], Q[l] + sum[j]);
} // k>=j
l = , r =;
for (j=m; j>=; --j) {
rpos = min(m, j+t);
tmp = dp[i-][j] + sum[j];
while (l<=r && Q[r]<=tmp)
--r;
Q[++r] = tmp;
P[r] = j;
while (P[l] > rpos)
++l;
dp[i][j] = max(dp[i][j], Q[l] - sum[j-]);
}
} int ans = -INF; rep(j, , m+)
ans = max(ans, dp[n][j]); printf("%d\n", ans);
} int main() {
ios::sync_with_stdio(false);
#ifndef ONLINE_JUDGE
freopen("data.in", "r", stdin);
freopen("data.out", "w", stdout);
#endif while (scanf("%d %d %d %d", &n, &m, &x, &t)!=EOF) {
rep(i, , n+)
rep(j, , m+)
scanf("%d", &score[i][j]);
solve();
} #ifndef ONLINE_JUDGE
printf("time = %d.\n", (int)clock());
#endif return ;
}
数据发生器。
from copy import deepcopy
from random import randint, shuffle
import shutil
import string def GenDataIn():
with open("data.in", "w") as fout:
t = 10
bound = 10**5
# fout.write("%d\n" % (t))
for tt in xrange(t):
n = randint(1, 100)
m = randint(1, 10000)
x = randint(1, m)
t = randint(1, m)
fout.write("%d %d %d %d\n" % (n, m, x, t))
for i in xrange(n):
L = []
for j in xrange(m):
x = randint(-500, 500)
L.append(x)
fout.write(" ".join(map(str, L)) + "\n") def MovDataIn():
desFileName = "F:\eclipse_prj\workspace\hdoj\data.in"
shutil.copyfile("data.in", desFileName) if __name__ == "__main__":
GenDataIn()
MovDataIn()