【POJ 3269】Building A New Barn
Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 1773 | Accepted: 571 |
Description
After scrimping and saving for years, Farmer John has decided to build a new barn. He wants the barn to be highly accessible, and he knows the coordinates of the grazing spots of all N (2 ≤ N ≤ 10,000 cows. Each grazing spot is at a point with integer coordinates (Xi, Yi) (-10,000 ≤ Xi ≤ 10,000; -10,000 ≤ Yi ≤ 10,000). The hungry cows never graze in spots that are horizontally or vertically adjacent.
The barn must be placed at integer coordinates and cannot be on any cow's grazing spot. The inconvenience of the barn for any cow is given the Manhattan distance formula | X - Xi | + | Y - Yi|, where (X, Y) and (Xi, Yi) are the coordinates of the barn and the cow's grazing spot, respectively. Where should the barn be constructed in order to minimize the sum of its inconvenience for all the cows?
Input
Lines 2..N+1: Line i+1 contains two space-separated integers which are the grazing location (Xi, Yi) of cow i
Output
Sample Input
4 1 -3 0 1 -2 1 1 -1
Sample Output
10 4
Hint
Source
#include<cstdio> #include<cstring> #include<algorithm> using namespace std; struct Vertex { int x, y; }v[10005]; int n, left, right, up, down, mid, cost; bool cmp1(Vertex A, Vertex B) { return (A.x < B.x || (A.x == B.x && A.y < B.y)); } bool cmp2(Vertex A, Vertex B) { return A.y < B.y; } int main() { scanf("%d", &n); for (int i = 0; i < n; ++i) scanf("%d%d", &v[i].x, &v[i].y); sort(v, v + n, cmp1); mid = n >> 1; left = v[mid - 1].x; right = v[mid + (n & 1)].x; sort(v, v + (n >> 1), cmp2); sort(v + (n >> 1) + (n & 1), v + n, cmp2); cost = 0; int l = 0, r = n - 1; up = 10005; down = -10005; while (l < r) { cost += abs(v[l].x - v[r].x) + abs(v[l].y - v[r].y); up = min(up, max(v[l].y, v[r].y)); down = max(down, min(v[l].y, v[r].y)); l++; r--; } if (n & 1) { int f = 4; if (v[mid].x >= left && v[mid].x <= right && v[mid].y >= down && v[mid].y <= up) { if (v[mid].x == left) f--; if (v[mid].x == right) f--; if (v[mid].y == up) f--; if (v[mid].y == down) f--; printf("%d %d\n", cost + 1, f); } else { if (down > v[mid].y) { cost += down - v[mid].y; if (left == v[mid].x || right == v[mid].x) cost++; printf("%d 1\n", cost); } else if (up < v[mid].y) { cost += v[mid].y - up; if (left == v[mid].x || right == v[mid].x) cost++; printf("%d 1\n", cost); } } } else { int del = 0; for (int i = 0; i < n; ++i) if (left <= v[i].x && right >= v[i].x && down <= v[i].y && up >= v[i].y) del++; printf("%d %d\n", cost, (right - left + 1) * (up - down + 1) - del); } return 0; }