G - Radar Scanner Gym - 102220G(一对矩形移动全部包涵一个点,最少的步数)

G - Radar Scanner Gym - 102220G
There are n rectangle radar scanners on the ground. The sides of them are all paralleled to the axes. The i-th scanner’s bottom left corner is square (ai,bi) and its top right corner is square (ci,di). 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 T(1≤T≤1000), denoting the number of test cases.

In each test case, there is one integer n(1≤n≤100000) in the first line, denoting the number of radar scanners.

For the next n lines, each line contains four integers ai,bi,ci,di(1≤ai,bi,ci,di≤109,ai≤ci,bi≤di), denoting each radar scanner.

It is guaranteed that ∑n≤106.

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
其实我们完全可以把方块看成一个点(x,y),意思就是找一个点到所有矩形的距离加和最小(反向分析就是把所有矩形移动到点(x,y),移动的距离最小,满足题意)。x和y轴方向的移动的思路都一样(要先移动到坐标x位置,再移动到y位置),所以我们可以选择其中一个方向来分析。对于x轴方向上移动来说,每条线段到x的距离为 (abs(A-x)+abs(B-x)-abs(A-B))/ 2,把所有线段到x的距离加起来就是\sum(abs(Ai-x)+abs(Bi-x)-abs(Ai-Bi))/ 2(i:0~n-1),\sumabs(Ai-Bi)是所有线段的长度,为一个定值。所以说,题目又能变成求所有点到x的最小距离,就是求所有\sumabs(Ai-x)+abs(Bi-x)最小,很显然当x是所有A,B的中位数的时候最小。
转载于:https://blog.csdn.net/Gold_Medal/article/details/107875773

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxx = 1e6 + 100;
ll x[maxx], y[maxx];
int n, t;
int main()
{
    ios::sync_with_stdio(0);
    cin >> t;
    while (t--)
    {
        cin>>n;
        ll ans=0; ll x1,x2,y1,y2;
        for(int i=0; i<n; i++)
        {
           
            cin>>x1>>y1>>x2>>y2;
            ans-=yy2-yy1+xx2-xx1; //先将总的线段长度减去
            x[i]=x1;  //记录点
            y[i]=y1;
            x[i+n]=x2;
            y[i+n]=y2;
        }
        sort(x,x+2*n);//排序,
        sort(y,y+2*n);
        ll xx=x[n-1],yy=y[n-1];//找中位数
        for(int i=0; i<n*2; i++)
        {                  //看与中位数的距离
            ans+=abs(x[i]-xx)+abs(y[i]-yy);
        }
        printf("%lld\n",ans/2);

    }
}

©️2020 CSDN 皮肤主题: 1024 设计师:上身试试 返回首页