As we know, DZY loves playing games. One day DZY decided to play with a n × m matrix. To be more precise, he decided to modify the matrix with exactly k operations.
Each modification is one of the following:
- Pick some row of the matrix and decrease each element of the row by p. This operation brings to DZY the value of pleasure equal to the sum of elements of the row before the decreasing.
- Pick some column of the matrix and decrease each element of the column by p. This operation brings to DZY the value of pleasure equal to the sum of elements of the column before the decreasing.
DZY wants to know: what is the largest total value of pleasure he could get after performing exactly k modifications? Please, help him to calculate this value.
InputThe first line contains four space-separated integers n, m, k and p (1 ≤ n, m ≤ 103; 1 ≤ k ≤ 106; 1 ≤ p ≤ 100).
Then n lines follow. Each of them contains m integers representing aij (1 ≤ aij ≤ 103) — the elements of the current row of the matrix.
Output a single integer — the maximum possible total pleasure value DZY could get.
2 2 2 2 1 3 2 4
11
2 2 5 2 1 3 2 4
11
For the first sample test, we can modify: column 2, row 2. After that the matrix becomes:
1 1 0 0
For the second sample test, we can modify: column 2, row 2, row 1, column 1, column 2. After that the matrix becomes:
-3 -3 -2 -2
遍历对象更换为k,在k确定的情况下求解
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <fstream>
#include <algorithm>
#include <queue>
#include <climits>
#include <cstring>
#include <string>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <vector>
#include <list>
const int maxn=5e2+10;
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int N = 1e6+5;
int a[1010][1010];
ll n,m,k,p;
ll sumx[1010];
ll sumy[1010];
ll dpx[1000010];
ll dpy[1000010];
priority_queue <ll> sx,sy;//有序数组
int main()
{
ios::sync_with_stdio(false);
cin>>n>>m>>k>>p;
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
cin >> a[i][j];
sumy[j] += a[i][j];
sumx[i] += a[i][j];
}
}
//行与列分开求
for(int i=0;i<n;i++)
sx.push(sumx[i]);
for(int j=0;j<m;j++)
sy.push(sumy[j]);
dpx[0] =dpy[0] = 0;
for(int i=1;i<=k;i++)
{
ll t1 = sx.top();
sx.pop();
ll t2 = sy.top();
sy.pop();
dpx[i] = dpx[i-1] + t1;
dpy[i] = dpy[i-1] + t2;
sx.push(t1-m*p);
sy.push(t2-n*p);
}
//最后利用k遍历
ll re = dpx[0]+dpy[k];
for(int i=1;i<=k;i++)
{
re = max(re,(dpx[i]+dpy[k-i]-(ll)(i*(k-i)*p)));
}
cout <<re<<endl;
return 0;
}