P9457 魔法少女扶苏(Hard Version)题解

· · 题解

原本只写了 div.4 的弱化版本,发现 Hard 版本只是改了数据范围。随便改改就过去了(逃)

我们假设一共释放 ans 次魔法,不难发现只要 ans 越大,符合条件的点就越多,于是这个问题具有单调性。题中要求的是最小的 ans,于是考虑使用二分答案。最开始 l 和 r 的范围应该是 1 到最大的 a_{i,j},由于 0 \leq a_{i.j} \leq 10^{11},时间并不大。

接下来考虑怎么写 check 函数。

我们设第 i 行上所有的点的和为 cntx_i,第 j 列上所有点的和为 cnty_j,不难得出 a_{i,j} 想要做出贡献,需要满足的条件为:

a_{i,j} - ans \geq cntx_i + cnty_j - (n+m) \times ans

但我们需要统计出至少有 k 个点满足条件,如果只是这样去一个一个 check 的话,时间依旧是 \mathcal{O}(nm) 的,无法接受。

考虑把它们全部移到左边去,得:

a_{i,j} - cntx_i - cnty_j + (n+m-1) \times ans \geq 0

其中 a_{i,j} - cntx_i - cnty_j 可以预处理出来。

因此我们不妨将所有的 a_{i,j}-s_{i,j} 从大到小排序,这样只要排序后的第 k 个点满足条件,那么前面的 k-1 个就一定满足条件(因为前面 k-1 个点的权值大于或等于第 k 个),这样每次 check 就是 \mathcal{O}(1) 的了。

总时间复杂度 \mathcal{O}(nm + \log n + \log m + \log P)。

温馨提示:记得开 long long。

#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
typedef long long ll;
const int maxn = 3e3 + 5;
const ll P = 1e11 + 5;

int n, m, k, tot;
ll cntx[maxn], cnty[maxn];

//快读 
ll read() {
    ll res = 0, flag = 1; char c = getchar();
    while(c < '0' || c > '9') { if(c == '-') flag = -1; c = getchar(); }
    while(c >= '0' && c <= '9') { res = res*10 + c - '0'; c = getchar(); }
    return res * flag; 
}

struct node {
    ll val; int x, y;
    bool operator < (const node& d) const {
        //从大到小排序 
        return val > d.val;
    }
} p[maxn*maxn];

bool check(ll mid) {
    if(p[k].val + 1ll* (n+m-1) * mid >= 0) return true;
    else return false;
}

int main() {
    scanf("%d %d %d", &n, &m, &k);
    for(int i = 1; i <= n; i++)
    for(int j = 1; j <= m; j++) {
        scanf("%lld", &p[++tot].val);
        //存到一个数组里,方便排序 
        p[tot].x = i, p[tot].y = j;
        cntx[i] += p[tot].val;
        cnty[j] += p[tot].val;
    }

    //求出a[i][j] - cntx[i] - cnty[j],并从大到小排序 
    for(int i = 1; i <= tot; i++)
        p[i].val -= cntx[p[i].x] + cnty[p[i].y];
    sort(p+1, p+1+tot);

    //二分 
    ll l = 0, r = P, ans = 0;
    while(l <= r) {
        ll mid = (l+r) >> 1;
        if(check(mid)) ans = mid, r = mid - 1;
        else l = mid + 1;
    }

    printf("%lld\n", ans);
    return 0;
}