【USACO06JAN && POJ3179】Corral the Cows

POJ

洛谷

分析

离散化+前缀和+二分

这题和激光炸弹很像,但由于坐标范围较大,需要用到二分。

代码

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#define il inline
#define maxn 10007
#define re register
#define tie0 cin.tie(0),cout.tie(0)
#define fastio ios::sync_with_stdio(false)
#define File(x) freopen(x".in","r",stdin);freopen(x".out","w",stdout)
using namespace std;
typedef long long ll;

template <typename T> inline void read(T &x) {
    T f = 1; x = 0; char c;
    for (c = getchar(); !isdigit(c); c = getchar()) if (c == '-') f = -1;
    for ( ; isdigit(c); c = getchar()) x = x * 10 + (c ^ 48);
    x *= f;
}

struct pos {
    int x, y;
}p[maxn>>1];

int n, c, cx, cy;
int x[maxn>>1], y[maxn>>1], hx[maxn], hy[maxn], sum[maxn>>1][maxn>>1];

bool check(int lim) {
    for (int i = hx[lim]; i <= cx; ++i)
        for (int j = hy[lim]; j <= cy; ++j) {
            int x0 = 0, y0  = 0;
            if (x[i] - lim >= 0) x0 = hx[x[i]-lim];
            if (y[j] - lim >= 0) y0 = hy[y[j]-lim];
            if (sum[i][j] + sum[x0][y0] - sum[i][y0] - sum[x0][j] >=c ) return 1;
        }
    return 0;
}

int main() {
    read(c), read(n);
    for (int i = 1; i <= n; ++i) {
        read(p[i].x), read(p[i].y);
        hx[p[i].x]++, hy[p[i].y]++;
    }
    for (int i = 1; i <= 10000; ++i) {
        if (hx[i]) x[++cx] = i; hx[i] = cx;
        if (hy[i]) y[++cy] = i; hy[i] = cy;
    }
    for (int i = 1; i <= n; ++i) sum[hx[p[i].x]][hy[p[i].y]]++;
    for (int i = 1; i <= cx; ++i)
        for (int j = 1; j <= cy; ++j)
            sum[i][j] += sum[i-1][j] + sum[i][j-1] - sum[i-1][j-1];
    int l = 1, r = 10000;
    while (l < r) {
        int mid = l + r >> 1;
        if (check(mid)) r = mid;
        else l = mid + 1;
    }
    printf("%d", l);
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/hlw1/p/11409427.html