货仓选址 排序后找中间的店

链接:https://ac.nowcoder.com/acm/contest/1001/B
来源:牛客网

题目描述
在一条数轴上有N家商店,它们的坐标分别为 A[1]~A[N]。现在需要在数轴上建立一家货仓,每天清晨,从货仓到每家商店都要运送一车商品。为了提高效率,求把货仓建在何处,可以使得货仓到每家商店的距离之和最小。
输入描述:

第一行一个整数N,第二行N个整数A[1]~A[N]。

输出描述:

一个整数,表示距离之和的最小值。

示例1
输入
复制

4
6 2 9 1

输出
复制

12

备注:

对于100%的数据:N≤100000N\leq 100000N≤100000, A[i]≤1000000A[i]\leq 1000000A[i]≤1000000

排个序,找中间的店建仓库
a [ ( n + 1 ) / 2 ] , ( a [ 1 ] + a [ n ] ) / 2 是a[(n+1)/2], 而不是(a[1]+a[n])/2 a[(n+1)/2],(a[1]+a[n])/2

#define debug
#ifdef debug
#include <time.h>
#include "/home/majiao/mb.h"
#endif

#include <iostream>
#include <algorithm>
#include <vector>
#include <string.h>
#include <map>
#include <set>
#include <stack>
#include <queue>
#include <math.h>

#define MAXN ((int)1e5+7)
#define ll long long int
#define INF (0x7f7f7f7f)
#define fori(lef, rig) for(int i=lef; i<=rig; i++)
#define forj(lef, rig) for(int j=lef; j<=rig; j++)
#define fork(lef, rig) for(int k=lef; k<=rig; k++)
#define QAQ (0)

using namespace std;

#define show(x...) \ do { \ cout << "\033[31;1m " << #x << " -> "; \ err(x); \ } while (0)

void err() { cout << "\033[39;0m" << endl; }
template<typename T, typename... A>
void err(T a, A... x) { cout << a << ' '; err(x...); }

namespace FastIO{

	char print_f[105];
	void read() {}
	void print() { putchar('\n'); }

	template <typename T, typename... T2>
		inline void read(T &x, T2 &... oth) {
			x = 0;
			char ch = getchar();
			ll f = 1;
			while (!isdigit(ch)) {
				if (ch == '-') f *= -1; 
				ch = getchar();
			}
			while (isdigit(ch)) {
				x = x * 10 + ch - 48;
				ch = getchar();
			}
			x *= f;
			read(oth...);
		}
	template <typename T, typename... T2>
		inline void print(T x, T2... oth) {
			ll p3=-1;
			if(x<0) putchar('-'), x=-x;
			do{
				print_f[++p3] = x%10 + 48;
			} while(x/=10);
			while(p3>=0) putchar(print_f[p3--]);
			putchar(' ');
			print(oth...);
		}
} // namespace FastIO
using FastIO::print;
using FastIO::read;

int n, m, Q, K;

#include <stdlib.h>
int main() {
#ifdef debug
	freopen("test", "r", stdin);
	clock_t stime = clock();
#endif
	read(n);
	int a[MAXN];
	for(int i=1; i<=n; i++) read(a[i]);
	sort(a+1, a+1+n);
	int now = a[(n+1)/2];
	int ans = 0;
	for(int i=1; i<=n; i++)
		ans += abs(a[i] - now);
	printf("%d\n", ans);


#ifdef debug
	clock_t etime = clock();
	printf("rum time: %lf 秒\n",(double) (etime-stime)/CLOCKS_PER_SEC);
#endif 
	return 0;
}




全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务