Question: Give You A matrix. Each time you select a row or column, the value is the sum of the rows or columns, and then subtract P from each element of the row. Ask the maximum total value that can be obtained for K consecutive times.
Solution:
If p = 0, that is, it will never be reduced, then the optimal one is to take the maximum K times of each row or column, so the optimal solution is introduced.
If no matter P, take it first, and then subtract the intersection of the rows and columns, because the value of each vertex can only be obtained once, and the value of the intersection is added twice, it must be removed once, if Row A is used and column B is used, the final answer is:
Res = dp1 [a] + dp2 [B]-B * (k-a) * P. You can take a closer look at the following part.
Where:
Dp1 [a] indicates the maximum sum (p) obtained after a is obtained in the row)
Dp2 [B] indicates the maximum sum (~) obtained by B in the column (~)
The maximum value can be obtained by using the priority queue. This is the idea.
Code:
#include <iostream>#include <cstdio>#include <cstring>#include <cmath>#include <cstdlib>#include <algorithm>#include <queue>#define lll __int64using namespace std;#define N 1007#define M 33lll dp1[N*N],dp2[N*N];lll RS[N],CS[N];lll a[N][N];priority_queue<lll> que;int main(){ int n,m,k,p; int i,j; while(scanf("%d%d%d%d",&n,&m,&k,&p)!=EOF) { memset(RS,0,sizeof(RS)); memset(CS,0,sizeof(CS)); for(i=1;i<=n;i++) { for(j=1;j<=m;j++) { scanf("%I64d",&a[i][j]); RS[i] += a[i][j]; CS[j] += a[i][j]; } } dp1[0] = dp2[0] = 0; while(!que.empty()) que.pop(); for(i=1;i<=n;i++) que.push(RS[i]); for(i=1;i<=k;i++) { lll tmp = que.top(); que.pop(); dp1[i] = dp1[i-1]+tmp; tmp -= (lll)m*p; que.push(tmp); } while(!que.empty()) que.pop(); for(i=1;i<=m;i++) que.push(CS[i]); for(i=1;i<=k;i++) { lll tmp = que.top(); que.pop(); dp2[i] = dp2[i-1]+tmp; tmp -= (lll)n*p; que.push(tmp); } ll res = dp1[0]+dp2[k]; for(i=1;i<=k;i++) { ll tmp = dp1[i]+dp2[k-i]-1LL*i*(k-i)*p; res = max(res,tmp); } printf("%I64d\n",res); } return 0;}View code