SwustOj A simple problem(0093)

一只聪明的猫提出了一个有趣的数学问题:如何将2n个玩具分成两组,每组n个,使得两组中对应位置玩具编号之差的绝对值之和最小。此问题考验的是数据排序与配对技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Dreamone has a lovely cat. The cat can comfort you if you are very dejected, she can also play with you if you are very bored. So Dreamone loves her very much. Of course, you bet, she can also make you trouble if she wants to be naughty. This time, she comes up with a simple problem for fun, just like this: She has 2n toys. In her heart, she has used a number to stand for each toy, and for example, the 2n toys are given like this: A1、A2、A3、….A2n-1、A2n She wants to divide them into two groups, where each group contains n toys. So we can use B1、B2...Bn ,which are all from A1、A2...A2n ,to stand for Group One ,use C1、C2….Cn ,which are all from A1、A2...A2n, to stand for Group Two. The cat wants to know the minimum value S for the expression below: S=|B1-C1|+|B2-C2|+|B3-C3|+...+|Bn-Cn| As we know Dreamone is studying MaJiang recently, so he has no time to solve the simply problem. But he knows the 6th program contest of SWUST is on, so he turns to you for help. Can you help him?

Description

The first line of input will be a positive integer C indicating how many data sets will be included. Each of the C data sets will contain two parts:The first part contains a number n(1<=n<=100000),and the second parts contains 2n numbers ,which are A1、A2、A2n-1、A2n (0<=Ai<=1000(1<=i<=2n)),represented 2n toys

Input

For each case, output the minimum value S for answer.

Output
1
2
3
4
5
2
1
1 3
2
1 1 1 2
Sample Input
1
2
2
1
#include<stdio.h>
#include<algorithm>
#include<iostream>
using namespace std;
int a[200005];
int main()
{
	int t;
	cin >> t;
	while (t--)
	{
		int n;
		cin >> n;
		n *= 2;
		for (int i = 0; i < n; i++)
		{
			scanf("%d", &a[i]);
		}
		sort(a, a + n);
		int ans = 0;
		for (int i = 0; i < n; i+=2)
		{
			ans += abs(a[i] - a[i + 1]);
		}
		cout << ans << endl;
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值