DFS嵌套DFS
//156K 47MS
#include <cstdio>
#include <cstring>
#include <iostream>
#include <cmath>
#include <algorithm> //不加此头文件min和abs在一起会出现编译错
using namespace std;
const int inf = 0x7fffffff;
int num[11];
bool usea[11], useb[11];
int cnt, cnta, cntb, val, ans;
char ch;
int pow(int a, int n){
int res = 1;
while(n){
if(n&1) res *= a;
a *= a;
n >>= 1;
}
return res;
}
void DFS_B(int vals, int deep){
if(deep > 0 && abs(val - vals * pow(10, (cntb-deep))) >= ans) return; //剪枝
if(deep == cntb){
ans = min(ans, abs(vals - val));
return;
}
for(int i=0; i<cnt; i++)
if(!usea[i] && !useb[i]){
if(deep == 0&& num[i] == 0) continue;
useb[i]=1;
DFS_B(vals*10+num[i], deep+1);
useb[i]=0;
}
}
void DFS_A(int vals,int deep){
if(deep == cnta){
val = vals;
memset(useb, 0, sizeof(useb));
DFS_B(0,0);
}
else{
for(int i=0; i<cnt; i++)
if(!usea[i]){
if(deep==0 && num[i]==0) continue;
usea[i]=1;
DFS_A(vals*10+num[i], deep+1);
usea[i]=0;
}
}
}
int main(){
int T;
while(scanf("%d",&T) != EOF){
getchar();
while(T--){
cnt=0;
while((ch=getchar()) != '\n'){
if(ch >= '0' && ch<='9')
num[cnt++] = ch-'0';
}
cnta = cnt>>1;
cntb = cnt-cnta;
ans = inf;
DFS_A(0,0);
if(ans==inf) printf("%d\n",val);
else printf("%d\n",ans);
}
}
return 0;
}