思路:对数进行全排列,然后切割,计算两数之差的绝对值,不断更新结果
使用algorithm中的next_permutation()函数:
用法:
next_permutation(start,end);(start和end分别为数组的头和尾指针)
作用是将更新数组中元``素的排列顺序,新排列的字典序是所有字典序大于原排列的排列中最小的那个,即不存在排列x,使得字典序大小为为:
原排列<x<新排列
若是下一个排列存在,即存在比当前排列字典序更大的排列存在,返回值为true
若下一个排列不存在,返回false
#include <cstdio>
#include <cstring>
#include <stack>
#include <queue>
#include <algorithm>
#include<iostream>
#include<map>
using namespace std;
#define MAX_A 10000
int main(){
int t;
scanf("%d",&t);
getchar();
int array[11];
while(t--){
int result = -1;//要输出的结果
//输入数组
char c;
int n = 0;
while(1){
scanf("%c",&c);
if(c=='\n'){
break;
}else if(c==' '){
continue;
}else{
array[n] = c-'0';
n++;
}
}
do{
//把数切割成两个
int a = 0,b = 0;
int k;
for(k=0;k<n/2;k++){
a = a*10+array[k];
}
for(k=n/2;k<n;k++){
b = b*10+array[k];
}
//把开头为0的情况排除
if((array[0]==0&&n/2!=1)||(array[n/2]==0&&(n-n/2)!=1)){
continue;
}
//得到两个数之差的绝对值
int dif = a-b;
if(dif<0){
dif = -dif;
}
if(result==-1||dif<result){
result = dif;
}
}while(next_permutation(array,array+n));
printf("%d\n",result);
}
return 0;
}