题意:有一个n*m的矩阵,每格有一个分数,一个人站在(1,x)位置,在每一行中,他只能朝一个方向走(向左或向右),且最多走t步,问走到最后第n行得到的最大分数。
思路:不难想到状态转移方程dp[i][j] = max(dp[i-1][k]+sum[i][j]-sum[i][k-1]),(k<j)
移项得
dp[i][j]-sum[i][j] = max(dp[i-1][k] - sum[i][k-1]);
方程右侧与i,j无关,所以可以用单调队列维护max(dp[i-1][k] - sum[i][k-1])的最值。
#include<cstdio> #include<cstring> #include<cmath> #include<cstdlib> #include<iostream> #include<algorithm> #include<vector> #include<map> #include<queue> #include<stack> #include<string> #include<map> #include<set> #define eps 1e-6 #define LL long long #define pii (pair<int, int>) //#pragma comment(linker, "/STACK:1024000000,1024000000") using namespace std; const int maxn = 10050; const int INF = 0x3f3f3f3f; int n, m, x, t, a[105][10050], d[105][10050], su[105][10050]; //单调队列 int qmin[maxn], vmin[maxn], hmin = 1, tmin = 0; void Min(int a, int i) { //第i个元素a入队 while(hmin<=tmin && vmin[hmin] < i-t) hmin++; //超范围队首出队 //while(hmin<=tmin && qmin[tmin]>=a) tmin--; //不符合要求队尾出列 int l = hmin, r = tmin; while(l <= r) { int m = l+(r-l)/2; if(qmin[m] <= a) r = m - 1; else l = m + 1; } tmin = ++r; qmin[tmin] = a; vmin[tmin] = i; } int main() { //freopen("input.txt", "r", stdin); while(scanf("%d%d%d%d", &n, &m, &x, &t) == 4) { for(int i = 1; i <= n; i++) for(int j = 1; j <= m; j++) scanf("%d", &a[i][j]), su[i][j]=su[i][j-1]+a[i][j]; for(int j = 1; j <= m; j++) if(j>=x-t && j<=x) d[1][j] = su[1][x] - su[1][j-1]; else if(j>x && j<=x+t) d[1][j] = su[1][j] - su[1][x-1]; else d[1][j] = -INF; for(int i = 2; i <= n; i++) { hmin = 1; tmin = 0; for(int j = 1; j <= m; j++) { Min(d[i-1][j]-su[i][j-1], j); d[i][j] = qmin[hmin]+su[i][j]; } hmin = 1; tmin = 0; for(int j = m; j > 0; j--) { Min(d[i-1][j]+su[i][j], m-j+1); d[i][j] = max(d[i][j], qmin[hmin]-su[i][j-1]); } } int ans = 0; for(int j = 1; j <= m; j++) ans = max(ans, d[n][j]); cout << ans << endl; } return 0; }
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-11-09 06:28:00