给定若干位十进制数,你可以通过选择一个非空子集并以某种顺序构建一个数。剩余元素可以用相同规则构建第二个数。除非构造的数恰好为0,否则不能以0打头。
举例来说,给定数字0,1,2,4,6与7,你可以写出10和2467。当然写法多样:210和764,204和176,等等。最后一对数差的绝对值为28,实际上没有其他对拥有更小的差。
Input - 输入
输入第一行的数表示随后测试用例的数量。
对于每组测试用例,有一行至少两个不超过10的十进制数字。(十进制数字为0,1,…,9)每行输入中均无重复的数字。数字为升序给出,相隔恰好一个空格。
Output - 输出
对于每组测试用例,输出一个以上述规则可获得的最小的差的绝对值在一行。
Sample Input - 输入样例
1
0 1 2 4 6 7
Sample Output - 输出样例
28
这道题目是个全排列搜索最优答案的题目,我们借助全排列函数(毕竟数据量不大)来完成搜索到所有的情况,然后从中截取两个数出来,穷尽搜索,但是也是有限制条件的,两个数字的首位不能是0.
代码:
#include<iostream>
#include<stdio.h>
#include<string>
#include<string.h>
#include<queue>
#include<algorithm>
const int maxn=5005;
typedef long long ll;
using namespace std;
typedef pair<ll,ll> p;
#include<string>
int a[maxn];
int permutation(int *b,int n)
{
int inf=99999999;
int i;
do
{
if(b[0]==0)
continue;
int mid=(n+1)/2;
int c=0,d=0;
if(b[mid])
{
for(i=0;i<mid;i++)
{
c=c*10+a[i];
}
for(i=mid;i<n;i++)
{
d=d*10+a[i];
}
inf=min(inf,abs(c-d));
}
}while(next_permutation(b,b+n));
return inf;
}
int main()
{
int i;
int n;
cin>>n;
getchar();
while(n--)
{
int k=0;
string s;
getline(cin,s);
for(i=0;i<s.length();i++)
if(s[i]>='0'&&s[i]<='9')
a[k++]=s[i]-'0';
if(k==2)
{
cout<<a[1]-a[0]<<endl;
continue;
}
cout<<permutation(a,k)<<endl;
}
return 0;
}