[Codeforces446B]DZY Loves Modification

描述 Description

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.

输入格式 InputFormat

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

输出格式 OutputFormat

Output a single integer — the maximum possible total pleasure value DZY could get.

样例输入 SampleInput

2 2 5 2
1 3
2 4

样例输出 SampleOutput

11

数据范围和注释 Hint

For the first sample test, we can modify: column 2, row 2, row 1, column 1, column 2. After that the matrix becomes:

-3 -3

-2 -2


Codeforces 446B


代码 Code

用 fr[i] 表示共选 i 行所能取得的最大快乐值,fc[i] 表示共选 i 列所能取得的最大快乐值。答案为 Max{fr[i]+fc[k-i]-i(k-i)p},0≤i≤k。

预处理用两个单调队列求得 fr[] 和 fc[]。注意要开 long long 及 ans 初始值应为非常小的负数。

#include <stdio.h>
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <queue>
using namespace std;
#define ll long long
const ll inf=0x7fffffff/27.11;
ll a[1005][1005];
ll fc[1000005],fr[1000005];
ll i,j,t,n,m,l,r,k,z,y,x,p;
ll ans;
priority_queue <ll> qc,qr;
inline void read(ll &x)
{
    x=0;char ch=getchar();
    while (ch<'0' || ch>'9') ch=getchar();
    while (ch>='0' && ch<='9') x=x*10+ch-'0',ch=getchar();
}
int main()
{
    read(n);read(m);read(k);read(p);
    for (i=1;i<=n;i++) for (j=1;j<=m;j++) read(a[i][j]);
    ans=-inf*inf;
    fr[0]=fc[0]=0;
    for (i=1;i<=n;i++)
    {
        t=0;
        for (j=1;j<=m;j++) t+=a[i][j];
        qr.push(t);
    }
    for (i=1;i<=m;i++)
    {
        t=0;
        for (j=1;j<=n;j++) t+=a[j][i];
        qc.push(t);
    }
    for (i=1;i<=k;i++)
    {
        t=qr.top();
        qr.pop();
        fr[i]=fr[i-1]+t;
        qr.push(t-p*m);
    }
    for (i=1;i<=k;i++)
    {
        t=qc.top();
        qc.pop();
        fc[i]=fc[i-1]+t;
        qc.push(t-p*n);
    }
    for (i=0;i<=k;i++) ans=max(ans,fr[i]+fc[k-i]-(ll)i*(k-i)*p);
    printf("%I64d\n",ans);
    return 0;
}