【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];

inline int iread() {
	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() {
	n = iread();
	for(int i = 1; i <= n; i++) {
		int x = iread(), y = iread();
		p[i] = (_point){x, y};
	}

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

	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值