Radar Scanner
题目
题意
给你几个方块,告诉你他的坐标等各种信息,方块可以上下左右走,问你如何走最小的路,让所以的方块都有一个共同的点(所以方块在该处重合)。
思路
因为不能斜着走,所以两点距离表示为|x1-x2|+|y1-y2|;
同时,因为是n个方块,所以所有的方块都可以向中心靠拢,因此问题变为了找所以点的中位数,这个中位数可以分为x,y两个方向,就像电影里的扫描,一条横线从上往下扫,另一条竖线从左往右扫,最后两条线相交扫描到位置,找到中位数后跑一遍距离即可。
代码
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
typedef long long ll;
const int N = 1e5 + 10;
struct node {
ll a, b, c, d;
} st[N];
ll dx[N], dy[N];
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t;
cin >> t;
while(t--) {
int n;
cin >> n;
vector<ll> dx, dy;
for(int i = 0; i < n; i++) {
cin >> st[i].a >> st[i].b >> st[i].c >> st[i].d;
dx.push_back(st[i].a); dx.push_back(st[i].c);
dy.push_back(st[i].b); dy.push_back(st[i].d);
}
sort(dx.begin(), dx.end());
sort(dy.begin(), dy.end());
ll sum = 0, x = dx[n - 1], y = dy[n - 1];
for(int i = 0; i < n; i++) {
ll a = st[i].a, b = st[i].b, c = st[i].c, d = st[i].d;
if(x > c || x < a) {
sum += min(abs(x - a), abs(x - c));
}
if(y > d || y < b) {
sum += min(abs(y - b), abs(y - d));
}
}
cout << sum << "\n";
}
return 0;
}
注意使用各种方法优化时间,这道题之前用数组一直T,换成vector就好了,离奇