描述N soldiers of the land Gridland are randomly scattered around the country.
A position in Gridland is given by a pair (x,y) of integer coordinates. Soldiers can move – in one move, one soldier can go one unit up, down, left or right (hence, he can change either his x or his y coordinate by 1 or -1).
The soldiers want to get into a horizontal line next to each other (so that their final positions are (x,y), (x+1,y), …, (x+N-1,y), for some x and y). Integers x and y, as well as the final order of soldiers along the horizontal line is arbitrary.
The goal is to minimise the total number of moves of all the soldiers that takes them into such configuration.
Two or more soldiers must never occupy the same position at the same time.
输入The first line of the input contains the integer N, 1 <= N <= 10000, the number of soldiers.
The following N lines of the input contain initial positions of the soldiers : for each i, 1 <= i <= N, the (i+1)st line of the input file contains a pair of integers x[i] and y[i] separated by a single blank character, representing the coordinates of the ith soldier, -10000 <= x[i],y[i] <= 10000.
输出The first and the only line of the output should contain the minimum total number of moves that takes the soldiers into a horizontal line next to each other.样例输入
5 1 2 2 2 1 3 3 -2 3 3
样例输出
8
题解:题目看起来很可怕,实际上就是有n个给出x,y坐标的点,这些点一次移动能够或上或下或左或右地移动一格,问最少移动多少格才能使坐标y都相等,坐标x都相邻。
实际上就是一个货仓选址问题,而且x,y是相互独立的两个问题。对于y,直接排序取中位数(或者直接取第k大数)。对于x,先排序,在对应减i,再排序取中位数。
注意最后计算总和时要取绝对值。
//#include<bits/stdc++.h> #include<algorithm> #include <iostream> #include <cstdlib> #include <cstring> #include <cassert> #include <cstdio> #include <vector> #include <string> #include <cmath> #include <queue> #include <stack> #include <set> #include <map> using namespace std; #define P(a,b,c) make_pair(a,make_pair(b,c)) #define rep(i,a,n) for (int i=a;i<=n;i++) #define per(i,a,n) for (int i=n;i>=a;i--) #define CLR(vis) memset(vis,0,sizeof(vis)) #define MST(vis,pos) memset(vis,pos,sizeof(vis)) #define pb push_back #define mp make_pair #define all(x) (x).begin(),(x).end() #define fi first #define se second #define SZ(x) ((int)(x).size()) typedef pair<int,pair<int,int> >pii; typedef long long ll; const ll mod = 1000000007; const int INF = 0x3f3f3f3f; ll gcd(ll a, ll b) { return b ? gcd(b, a%b) : a; } const int maxn=1e5+10; int x[maxn],y[maxn]; int main(){ int n; ll sum=0; cin>>n; rep(i,1,n)scanf("%d%d", &x[i], &y[i]); sort(x+1,x+n+1); sort(y+1,y+n+1); rep(i,1,n){ x[i]-=i; } sort(x+1,x+n+1); rep(i,1,n){ sum+=abs(y[i]-y[(n+1)/2]); sum+=abs(x[i]-x[(n+1)/2]); } cout<<sum; return 0; }