https://vijos.org/p/1039
使最大数最小,最小数最大即可。
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cstdlib>
#define ms(i,j) memset(i, j, sizeof(i));
using namespace std;
int a[11];
bool vi[11];
int main ()
{
int t;
scanf("%d", &t);
while (t--)
{
int first = 0, sec = 0;
int n;
int ans = 100000000;
scanf("%d", &n);
for (int i=0;i<n;i++)
{
scanf("%d", &a[i]);
}
if (n==2) {printf("%d\n", abs(a[1]-a[0])); continue;}
sort(a, a+n);
if (n%2==1)//奇数
{
//找最小不为0的数做大数的首位
int i = 0;
while (a[i]==0) i++;
ms(vi,false);
vi[i] = true;
first = first * 10 + a[i];
//构造最大数和最小数
i = 0;
int k = 0;//计数
while (k<n/2)
{
if (!vi[i])
{
vi[i] = true;
first = first * 10 + a[i];
k++;
}
i++;
}
i = n-1;
k = 0;//计数
while (k<n/2)
{
if (!vi[i])
{
vi[i] = true;
sec = sec * 10 + a[i];
k++;
}
i--;
}
printf("%d\n", abs(first-sec));
} else //偶数
{
//枚举两个相邻的数作两个数的首位
for (int i=0;i<n-1;i++) if (a[i]!=0&&a[i+1]!=0)
{
first = sec = 0;
ms(vi,false);
first = first * 10 + a[i]; vi[i] = true;
sec = sec * 10 + a[i+1]; vi[i+1] = true;
int j = 0;
int k = 0;
while (k<n/2-1)
{
if (!vi[j])
{
vi[j] = true;
sec = sec * 10 + a[j];
k++;
}
j++;
}
j = n-1;
k = 0;
while (k<n/2-1)
{
if (!vi[j])
{
vi[j] = true;
first = first * 10 + a[j];
k++;
}
j--;
}
ans = min(ans, abs(first-sec));
}
printf("%d\n", ans);
}
}
return 0;
}