[题解] 2019牛客暑期多校第三场H题 Magic Line

题目链接https://ac.nowcoder.com/acm/contest/883/H

题意:二维平面上有n个不同的点,构造一条直线把平面分成两个点数相同的部分。

题解:对这n个点以x为第一关键字,y为第二关键字从小到大排序。找到最中间两个点。然后以这两个点为界限,将平面划分为左右两个点数相同的区域。如图所示。

由于题目中给出点的坐标绝对值≤1000,而我们需要给出的点的坐标范围为1e9,因此必定可以找到这样一条很陡的直线。

AC代码

#include <bits/stdc++.h>
#define SIZE 1007
#define rep(i, a, b) for(int i = a; i <= b; ++i)
using namespace std;
typedef long long ll;
ll n, m, t;
struct Point {
	int x, y;
}p[SIZE];
double xx, yy;
bool cmpx(Point a, Point b) {
	if (a.x == b.x) return a.y < b.y;
	else return a.x < b.x;
}
int mm = 1e4;
int main() {
	cin >> t;
	while (t--) {
		cin >> n;
		double tx1, tx2, ty1, ty2;
		rep(i, 1, n) cin >> p[i].x >> p[i].y;
		sort(p + 1, p + n + 1, cmpx);
		tx1 = p[(n / 2)].x, ty1 = p[(n / 2)].y;	//中间的两个点
		tx2 = p[(n + 2) / 2].x, ty2 = p[(n + 2) / 2].y;
		double mx = 0.5 * (tx1 + tx2), my = 0.5 * (ty1 + ty2);	//中点坐标
		int rx1 = 0, rx2 = 0, ry1 = 0, ry2 = 0;
		if ((floor(mx) == floor(mx + 0.6))) rx1 = mx - 1, rx2 = mx + 1;	//把中点的x坐标偏移到最近的整数x坐标轴
		else {
			rx1 = floor(mx);
			rx2 = rx1 + 1;
		}
		if ((floor(my) == floor(my + 0.6))) ry1 = my + mm, ry2 = my - mm;	//y坐标偏移
		else {
			ry1 = floor(my) + 1 + mm;
			ry2 = floor(my) - mm;
		}
		cout << rx1 << ' ' << ry1 << ' ' << rx2 << ' ' << ry2 << endl;
	}
	return 0;
}

总结:赛场上由于忘记正负数使用int取整的结果不同,没用floor函数取整,导致罚时++,今后务必避免。

原文地址:https://www.cnblogs.com/st1vdy/p/11245932.html