poj 2718 Smallest Difference(穷竭搜索dfs)

时间:2021-04-03 09:01:23

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 , the integer may not start with the digit . 

For example, if you are given the digits , , , ,  and , you can write the pair of integers  and . Of course, there are many ways to form such pairs of integers:  and ,  and , etc. The absolute value of the difference between the integers in the last pair is , 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  decimal digits. (The decimal digits are , , ..., .) 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

     

Sample Output


Source

给你一些数,然后要求你使用这些数字组成2个数,然后求他们的差值最小。

思路:

有一个很重要的剪枝,若当前搜索的第二个数后面全部补零与第一个数所产生的差值比当前所搜索到的结果还要大,那么就直接返回。这个剪枝就是超时与几十MS的差距

注意一点就是可能有0 与一个数字存在的情况,比如0 3,0 5等等。

其他的就比较简单了

 #include<iostream>
#include<cstdio>
#include<cstring>
#include<set>
#include<map>
#include<algorithm>
#include<queue>
using namespace std;
#define inf 1<<29
#define N 16
int a[N];
int vis_a[N],vis_b[N];
int ans;
int Anum,Bnum;
int w;
int n;
int nums[]={,,,,,};
void dfs_B(int num,int vals,int sum){ if( num> && sum*nums[Bnum-num]-vals>=ans ) return; if(num==Bnum){
ans=min(ans,abs(sum-vals));
return;
} for(int i=;i<n;i++){
if(!vis_a[i] && !vis_b[i]){
if(num== && a[i]==)
continue;
vis_b[i]=;
dfs_B(num+,vals,sum*+a[i]);
vis_b[i]=;
}
} }
void dfs_A(int num,int vals){ if(num==Anum){
w=vals;
memset(vis_b,,sizeof(vis_b));
dfs_B(,vals,);
return;
} for(int i=;i<n;i++){
if(!vis_a[i]){
if(num== && a[i]==)
continue;
vis_a[i]=;
dfs_A(num+,vals*+a[i]);
vis_a[i]=;
}
}
}
int main()
{
int t; while(scanf("%d",&t)!=EOF)
{ getchar();
while(t--){
n=;
char ch;
while((ch=getchar())!='\n'){
if(ch>='' && ch<='')
a[n++]=ch-'';
} //for(int i=0;i<n;i++)
//printf("---%d\n",a[i]);
ans=inf; Anum=n>>;
Bnum=n-Anum; dfs_A(,); if(ans!=inf)
printf("%d\n",ans);
else
printf("%d\n",w);
} }
return ;
}