DZY Loves Modification CodeForces - 446B

DZY Loves Modification CodeForces - 446B

题目描述

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:

1.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.

2.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.

Input
The first line contains four space-separated integers n, m, k and p (1 ≤ n, m ≤ 10^3; 1 ≤ k ≤ 10^6; 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
Output a single integer — the maximum possible total pleasure value DZY could get.

Example

Input
2 2 2 2
1 3
2 4
Output
11

Input
2 2 5 2
1 3
2 4
Output
11

Note
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

大致题意
给你一个n*m的矩阵,然后你有k次操作,每次你可以将某一行或者某一列上的全部数字相加,得到一个价值,然后将所选的某行或某列上的每个数都减去p,累加每次操作后得到的价值,问经过k次操作后所能得到的最大值。

思路
通过分析,我们可以知道如果对行操作了x次,则每列的值都得减掉x*p,同理如果对列操作了y次,则每行的值都得减掉y*p。但是对于每一行的值的排序是不变的,对每一列的值的排序也是不变的。所以我们可以先将行和列分开考虑,预处理出单独操作行(1到k次)的最大价值,预处理出单独操作列(1到k次)的最大价值。然后枚举行操作多少次,列操作多少次。若行操作x次的最大价值H[x],列操作x的最大价值为L[x]。若行操作了i次,列操作k-i次,则答案为H[i]+L[k-i]-p*i*(k-i)。

代码如下

#include
#include
#include
#include
#include
#include
#include
#include
#define ll long long  
const int  Max =1e6+5;
using namespace std;

int n,m,k,p,A[1005][1005];
ll H[Max],L[Max],Ans=-(1LL<<60);

priority_queue<int> Q_H,Q_L;  //用优先队列来写

int main()
{

     scanf("%d %d %d %d",&n,&m,&k,&p);
     for(int i=0;ifor(int j=0;jscanf("%d",&A[i][j]);

       for(int i=0;iint tmp=0;
         for(int j=0;jfor(int j=0;jint tmp=0;
        for(int i=0;ifor(int i=1;i<=k;i++)
       {
        ll x=Q_H.top();
        Q_H.pop();
        H[i]=H[i-1]+x;
        Q_H.push(x-p*m);
       }

       for(int i=1;i<=k;i++)
       {
          ll x=Q_L.top();
          Q_L.pop();
          L[i]=L[i-1]+x;
          Q_L.push(x-p*n);
        }

    for (int i=0;i<=k;i++) 
    Ans=max(Ans,H[i]+L[k-i]-1LL*(k-i)*i*p);
    printf("%I64d\n",Ans);
   return 0;
}

你可能感兴趣的:(模拟,贪心,数论,优先队列)