AcWing 123 士兵 (扩展货仓选址)

https://www.acwing.com/problem/content/125/

可以发现,横纵坐标的移动是分开的,
所以先对 \(y\) 轴进行操作,就是普通的货仓选址问题

再考虑 \(x\) 轴,最终的排列,士兵的排列顺序一定是不变的,
假设第一个士兵移动到的位置是\(a\)
那么答案就是\(\sum{\mid x_i - a \mid}\)
于是对每个 \(x\) 减去 \(i-1\), 又转化成了货仓选址问题

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<cmath>
#include<stack>
#include<queue>
using namespace std;
typedef long long ll;

const int maxn = 10010;

int n;
int x[maxn], y[maxn];

ll read(){ ll s=0,f=1; char ch=getchar(); while(ch<'0' || ch>'9'){ if(ch=='-') f=-1; ch=getchar(); } while(ch>='0' && ch<='9'){ s=s*10+ch-'0'; ch=getchar(); } return s*f; }

int main(){
	n = read();
	for(int i=1;i<=n;++i) x[i] = read(), y[i] = read();
	
	sort(y + 1, y + 1 + n);
	int Mid = y[n / 2 + 1];
	
	ll ans = 0;
	for(int i=1;i<=n;++i) ans += abs(y[i] - Mid);
	
	sort(x + 1, x + 1 + n);
	for(int i=1;i<=n;++i) x[i] -= (i-1);
	sort(x + 1, x + 1 + n);
	
	Mid = x[n / 2 + 1];
	for(int i=1;i<=n;++i) ans += abs(x[i] - Mid);
	
	cout << ans << endl;
	
	return 0;
}
posted @ 2020-11-06 12:42  Tartarus_li  阅读(82)  评论(0编辑  收藏  举报