题目链接:http://codeforces.com/gym/102220/problem/G
Radar Scanner
There are ? rectangle radar scanners on the ground. The sides of them are all paralleled to the axes. The ?-th scanner’s bottom left corner is square (??,??) and its top right corner is square (??,??). Each scanner covers some squares on the ground.You can move these scanners for many times. In each step, you can choose a scanner and move it one square to the left, right, upward or downward.
Today, the radar system is facing a critical low-power problem. You need to move these scanners such that there exists a square covered by all scanners.Your task is to minimize the number of move operations to achieve the goal.
Input
The first line of the input contains an integer ?(1≤?≤1000), denoting the number of test cases. In each test case, there is one integer ?(1≤?≤100000)in the first line, denoting the number of radar scanners.
For the next ? lines, each line contains four integers ??,??,??,??(1≤??,??,??,??≤109,??≤??,??≤??), denoting each radar scanner.
It is guaranteed that ∑?≤10e6.
Output
For each test case, print a single line containing an integer, denoting the minimum number of steps.
Example
Input
1
2
2 2 3 3
4 4 5 5
Output
2
题意:
给定平面上 n 个边平行坐标轴的矩形,每个矩形覆盖若干方格。
用最少的操作次数上下左右移动这些矩形,使得存在一个点被所有矩形覆盖。
n ≤ 100000。
思路:
两维独立,考虑一维的情况。
假设最终交点为 x,则线段 [l, r] 移动到 x 的代价为
[|l−x|+|r−x|−(r−l)]/2。
除以 2 以及减去 r − l 的部分与 x 无关,只需要最小化
∑(|l − x| + |r − x|)。
经典问题,当 x 取所有 l, r 的中位数时最优。
时间复杂度 O(n)。
代码
#include<iostream>
#include<stdio.h>
#include<math.h>
#include<algorithm>
#include<string>
#include<cstring>
using namespace std;
typedef long long ll;
const int INF=0x3f3f3f3f;
const int MAX_N=100000+5;
const int MAX_M=1000+5;
int n;
int a[MAX_N][4];
int z[MAX_N*2];
ll get(int s,int t){
for(int i=0;i<n;i++){
z[i]=a[i][s];
z[i+n]=a[i][t];
}
sort(z,z+2*n);
ll res=0;
for(int i=0;i<2*n;i++){
res+=abs(z[i]-z[n]);
}
for(int i=0;i<n;i++){
res-=a[i][t]-a[i][s];
}
return res/2;
}
int main(){
int T;
scanf("%d",&T);
while(T--){
scanf("%d",&n);
for(int i=0;i<n;i++){
for(int j=0;j<4;j++){
scanf("%d",&a[i][j]);
}
}
ll res=0;
res+=get(1,3);
res+=get(0,2);
printf("%lld\n",res);
}
return 0;
}