Ultraviolet A 1511 Soju
Question Link
Given two point sets, the two points set must take the minimum Manhattan distance from each other to ensure that X of Point Set 1 is less than 0 and X of Point Set 2 is greater than 0.
Idea: Because X2> X1, you only need to consider the Y value. If one y is larger than the other y, It is Y1-Y2. Otherwise, it is Y2-Y1, in this way, you only need to perform two sort greedy computations for these two cases.
Code:
#include <cstdio>#include <cstring>#include <algorithm>using namespace std;const int INF = 0x3f3f3f3f;const int N = 200005;int t, n, m, a1, a2, a3, a4;struct Point { int x, y, flag;} p[N];bool cmp(Point a, Point b) { return a.y < b.y;}int solve() { int ans = INF; sort(p, p + n + m, cmp); int tmp = INF; for (int i = 0; i < n + m; i++) {if (p[i].flag) tmp = min(tmp, p[i].x - p[i].y);else ans = min(ans, p[i].y - p[i].x + tmp); } tmp = INF; reverse(p, p + n + m); for (int i = 0; i < n + m; i++) {if (p[i].flag) tmp = min(tmp, p[i].x + p[i].y);else ans = min(ans, -p[i].x - p[i].y + tmp); } return ans;}int main() { scanf("%d", &t); while (t--) {scanf("%d", &n);for (int i = 0; i < n; i++) { scanf("%d%d", &p[i].x, &p[i].y); p[i].flag = 0;}scanf("%d", &m);for (int i = n; i < n + m; i++) { scanf("%d%d", &p[i].x, &p[i].y); p[i].flag = 1;}printf("%d\n", solve()); } return 0;}