列表

详情


NC50956. Soliders

描述

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, , the number of soldiers. 
The following N lines of the input contain initial positions of the soldiers : for each i, , 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, .

输出描述

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.

示例1

输入:

5
1 2
2 2
1 3
3 -2
3 3

输出:

8

原站题解

上次编辑到这里,代码来自缓存 点击恢复默认模板

C++(g++ 7.5.0) 解法, 执行用时: 7ms, 内存消耗: 512K, 提交时间: 2023-07-17 09:38:34

#include<bits/stdc++.h>
using namespace std;
long long x[1000001],y[1000001];
int main(){
	long long n,ans=0;scanf("%lld",&n);
	for(register int i=1;i<=n;++i)scanf("%lld%lld",&x[i],&y[i]);
	sort(x+1,x+n+1);sort(y+1,y+n+1);
	for(register int i=1;i<=n;++i)x[i]-=i;
	sort(x+1,x+n+1);
	for(register int i=1;i<=n;++i)ans+=abs(x[i]-x[n/2+1])+abs(y[i]-y[n/2+1]);
	printf("%lld",ans);
} 

C++14(g++5.4) 解法, 执行用时: 6ms, 内存消耗: 500K, 提交时间: 2020-05-17 16:56:18

#include<bits/stdc++.h>
using namespace std;
const int N=10100;
int x[N],y[N],n;
int work(int x[])
{
	sort(x,x+n);
	int res=0;
	for(int i=0;i<n;i++)
	{
		res+=abs(x[i]-x[n/2]);
	}
	return res;
}
int main()
{
	scanf("%d",&n);
	for(int i=0;i<n;i++)
	{
		scanf("%d%d",&x[i],&y[i]);
	}
	sort(x,x+n);
	for(int i=0;i<n;i++)x[i]-=i;
	printf("%d\n",work(x)+work(y));
	return 0;
}

C++11(clang++ 3.9) 解法, 执行用时: 10ms, 内存消耗: 492K, 提交时间: 2020-03-03 22:19:38

#include<bits/stdc++.h>
using namespace std;
int n,x[10001],y[10001],s,d;
int main()
{
	cin>>n;
	for(int i=1;i<=n;i++) cin>>x[i]>>y[i];
	sort(y+1,y+n+1),sort(x+1,x+n+1);
	for(int i=1;i<=n;i++) x[i]-=i-1;
	sort(x+1,x+n+1);
	d=(n+1)/2;
	for(int i=1;i<=n;i++)
	s+=abs(x[i]-x[d])+abs(y[i]-y[d]);
	cout<<s;
}

上一题