Smallest Difference
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 13820 Accepted: 3739
Description
Given a number of distinct decimal digits, you can form one integer by choosing a non-empty subset of these digits and writing them in some order. The remaining digits can be written down in some order to form a second integer. Unless the resulting integer is 0, the integer may not start with the digit 0.
For example, if you are given the digits 0, 1, 2, 4, 6 and 7, you can write the pair of integers 10 and 2467. Of course, there are many ways to form such pairs of integers: 210 and 764, 204 and 176, etc. The absolute value of the difference between the integers in the last pair is 28, and it turns out that no other pair formed by the rules above can achieve a smaller difference.
Input
The first line of input contains the number of cases to follow. For each case, there is one line of input containing at least two but no more than 10 decimal digits. (The decimal digits are 0, 1, …, 9.) No digit appears more than once in one line of the input. The digits will appear in increasing order, separated by exactly one blank space.
Output
For each test case, write on a single line the smallest absolute difference of two integers that can be written from the given digits as described by the rules above.
Sample Input
1
0 1 2 4 6 7
Sample Output
28
Source
Rocky Mountain 2005
题目大意:给你一个递增的序列。其中数字的个数大于等于2 ,小于等于9;且两个序列不能以0开头。让你把这个序列重新组合后分为两个序列,使得这两个序列的值相减的差的绝对值最小。
思路:
因为范围很小,用next_permutation()找出所有符合条件的全排列 的可能性,对其分类求差。
#include<cstdio>
#include<algorithm>
#include<iostream>
#include<cstring>
using namespace std;
const int MAX = 1e6+10;
const int INF = 0x3fffffff;
int a[15];
int n;
void solve() {
while(a[0]==0)
next_permutation(a,a+n);//找出第一个数非零的总序列
int ans=INF;
int mid=(n+1)/2;
do {
if(a[mid]) {//当第二个序列的第一个数不是零的时候。
int x=a[0],y=a[mid];
for(int i=1;i<mid;i++)
x=x*10+a[i];//用前半段序列的值,计算第一个数,
for(int i=mid+1;i<n;i++)
y=y*10+a[i];//用后半段序列的值,计算第二个数
if(ans>abs(x-y))
ans=min(ans,abs(x-y));//求两个数的差
}
}while(next_permutation(a,a+n));//所有全排列的情况。
cout<<ans<<endl;
}
int main()
{
int t;
char c;
cin>>t;
getchar();
while(t--) {
n=0;
memset(a,0,sizeof(a));
while((c=getchar())!='\n') {
if(c!=' ')
a[n++]=c-'0';
}//找出总序列里的所有数字,存起来。
if(n==1) printf("%d\n",a[0]);//只有一个数的时候,差就是这个数
else if(n==2) printf("%d\n",abs(a[1]-a[0]));//只有两个数的时候,直接相减
else solve();
}
return 0;
}