# 【BZOJ1696】[Usaco2007 Feb]Building A New Barn新牛舍【中位数】【绝对值不等式】【贪心】

（1）奇，取最中间的点，如果上面无牛，直接算；如果有牛，那么取周围四个点，算。

（2）偶，取中间两个点，分别记为(x, y) (xx, yy)，那么最短距离确定了，点数为(xx - x + 1) * (yy - y + 1) - 内部的牛的个数

/* Pigonometry */
#include <cstdio>
#include <algorithm>

using namespace std;

typedef pair<int, int> pii;

const int maxn = 10005, inf = 0x3f3f3f3f;

int n;

struct _point {
int x, y;
} p[maxn];

int f = 1, x = 0; char ch = getchar();
for(; ch < '0' || ch > '9'; ch = getchar()) f = ch == '-' ? -1 : 1;
for(; ch >= '0' && ch <= '9'; ch = getchar()) x = x * 10 + ch - '0';
return f * x;
}

inline int intabs(int x) {
return x < 0 ? -x : x;
}

inline bool cmpx(_point a, _point b) {
return a.x < b.x;
}

inline bool cmpy(_point a, _point b) {
return a.y < b.y;
}

inline bool check(int x, int y) {
for(int i = 1; i <= n; i++) if(p[i].x == x && p[i].y == y)
return 1;
return 0;
}

inline void solveodd() {
sort(p + 1, p + n + 1, cmpx);
int x = p[(n >> 1) + 1].x;
sort(p + 1, p + n + 1, cmpy);
int y = p[(n >> 1) + 1].y;

int ans1 = inf, ans2 = 0;
if(check(x, y)) {
int dx[] = {1, 0, -1, 0}, dy[] = {0, -1, 0, 1};
for(int i = 0; i < 4; i++) {
int xx = x + dx[i], yy = y + dy[i], res = 0;
for(int i = 1; i <= n; i++) res += intabs(p[i].x - xx) + intabs(p[i].y - yy);
if(res < ans1) ans1 = res, ans2 = 1;
else if(res == ans1) ans2++;
}
} else {
for(int i = 1; i <= n; i++) ans1 += intabs(p[i].x - x) + intabs(p[i].y - y);
ans2 = 1;
}

printf("%d %d\n", ans1, ans2);
}

inline void solveeven() {
sort(p + 1, p + n + 1, cmpx);
int x = p[n >> 1].x, xx = p[(n >> 1) + 1].x;
sort(p + 1, p + n + 1, cmpy);
int y = p[n >> 1].y, yy = p[(n >> 1) + 1].y;

int ans1 = 0;
for(int i = 1; i <= n; i++) ans1 += intabs(p[i].x - x) + intabs(p[i].y - y);

int ans2 = (xx - x + 1) * (yy - y + 1);
for(int i = 1; i <= n; i++) if(p[i].x >= x && p[i].x <= xx && p[i].y >= y && p[i].y <= yy) ans2--;

printf("%d %d\n", ans1, ans2);
}

int main() {
for(int i = 1; i <= n; i++) {
p[i] = (_point){x, y};
}

if(n & 1) solveodd();
else solveeven();

return 0;
}


• 0
点赞
• 0
评论
• 0
收藏
• 一键三连
• 扫一扫，分享海报

11-01 556
08-19 1042
09-18 1608
03-03 1010
09-18 1595
10-31 986

BraketBN

¥2 ¥4 ¥6 ¥10 ¥20