Vadim is really keen on travelling. Recently he heard about kayaking activity near his town and became very excited about it, so he joined a party of kayakers.
Now the party is ready to start its journey, but firstly they have to choose kayaks. There are 2·n people in the group (including Vadim), and they have exactly n - 1 tandem kayaks (each of which, obviously, can carry two people) and 2 single kayaks. i-th person’s weight is wi, and weight is an important matter in kayaking — if the difference between the weights of two people that sit in the same tandem kayak is too large, then it can crash. And, of course, people want to distribute their seats in kayaks in order to minimize the chances that kayaks will crash.
Formally, the instability of a single kayak is always 0, and the instability of a tandem kayak is the absolute difference between weights of the people that are in this kayak. Instability of the whole journey is the total instability of all kayaks.
Help the party to determine minimum possible total instability!
Input
The first line contains one number n (2 ≤ n ≤ 50).
The second line contains 2·n integer numbers w1, w2, …, w2n, where wi is weight of person i (1 ≤ wi ≤ 1000).
Output
Print minimum possible total instability.
Example
Input
2
1 2 3 4
Output
1
Input
4
1 3 4 6 3 4 100 200
Output
5
因为只有两条单人皮艇,可以排除坐单人皮艇的两个人,剩下的数排序并求出相邻两数差值的和sum(最小的稳定性一定是排序后两两相邻数的差值之和),求出做小的sum
#include<iostream>
#include<stdio.h>
#include<algorithm>
#include<stdlib.h>
#include<string.h>
#include<vector>
#include<queue>
#include<stack>
#include<math.h>
#define me(a,b) memset(a,b,sizeof(a))
using namespace std;
const int manx=2e5+10;
int a[400];
int main()
{
int n,mix,weight;
while(scanf("%d",&n)!=EOF)
{
mix=10000;
int sum=0;
for(int i=0; i<2*n; i++)
scanf("%d",&a[i]);
sort(a,a+2*n);
for(int i=0; i<2*n; i++)
for(int j=i+1; j<2*n; j++)//j=i+1可以避免j和i重复的情况
{
weight=sum=0;
for(int l=0; l<2*n; l++)
if(l^i&&l^j)
{
if(weight)
{
sum+=a[l]-weight;
weight=0;
}
else
weight=a[l];
}
if(mix>sum)
mix=sum;
}
printf("%d\n",mix);
}
return 0;
}
最开始的想法是先排序,然后一次一次遍历数组(直到最后数组中元素个数为2),每次找出最小的相邻数的差值(每次遍历完后去掉这两个值)把每次的最小值加起来。但是,,,,,,交上去错了,,,
虽然每次找的是最小值,但最后的和并不一定是整体情况的最小值,比如这组数据//1 5 9 11 12 14,正确答案应该是4,而上述方法结果却是5