| Time Limit: 1000MS | Memory Limit: 65536K |
| Total Submissions: 20320 | Accepted: 5509 |
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
题意:
给出升序的几个数字,让你用这些数字组合出两个数字,求这两个数字最小的差
- 数字升序,且不重复。
- 组合的数字不能用0开头
- 数的数量为2-10,大小为0-9
注意:
- 注意只有0和一个数字的情况
解法:
使用next_permutation()函数来列出数字的全部排列组合,当全部排列组合后,该函数返回false。
对每种可能进行计算,算出最小的差即可
代码:
#include <stdio.h>
#include <iostream>
#include <algorithm>
using namespace std;
int ddata[14];
int parity;
int n,cnt,ans;
int num(int st, int ed){
int temp1 = 0;
for(int i = st; i <= ed; i++){
temp1 *= 10;
temp1 += ddata[i];
}
return temp1;
}
void solve(){
int mid = cnt / 2;
if(cnt == 2){
//防止出现只有0数字和其他数字的情况
ans = abs(ddata[0] - ddata[1]);
}else{
do{
//数字0开头跳过
if(ddata[0] == 0 || ddata[mid] == 0){
continue;
}
int tem1 = num(0,mid - 1);
int tem2 = num(mid, cnt - 1);
ans = min(ans , abs(tem1 - tem2));
}while(next_permutation(ddata,ddata + cnt));
}
cout << ans << endl;
}
int main(void){
scanf("%d",&n);
getchar();
while(n--){
cnt = 0;
ans = 0x3f3f3f3f;
//拿数据
do{
scanf("%d",&ddata[cnt++]);
}while(getchar() != '\n');
solve();
}
return 0;
}