ACM Smallest Difference(挑战程序设计竞赛)

来源:互联网 发布:linux jenkins 配置 编辑:程序博客网 时间:2024/06/05 09:09

Smallest Difference

Time Limit: 1000ms
Memory Limit: 65536KB
This problem will be judged on PKU. Original ID: 2718
64-bit integer IO format: %lld      Java class name: Main
Prev 
Submit Status Statistics Discuss
 Next
Type: 
None
     
    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

    10 1 2 4 6 7

    Sample Output

    28

    Source

    Rocky Mountain 2005
    题目大意:首行给出组数,每组一行数,求用这一行数组成的两个数的最小差值

    解题思路:深度优先搜索+剪枝
    剪枝方法:搜索时将第二个数未搜到的补0,如果不能时差值减小减掉
    #include <iostream>#include <cstring>#include <algorithm>#include <cstdio>using namespace std;#define MAX_N 10#define INF 1<<29int cnt;int num[MAX_N];int minabs;bool used[MAX_N];int n1,n2;int n1bak;int cnta,cntb;int base[]={0,10,100,1000,10000,100000,1000000};void DFS(int cur,int n){if(cur==n){minabs=min(minabs,abs(n1-n2));return;}else if(cur==cnta){n1bak=n1;}else if(cur>cnta){int t=n2*base[n-cur];int t2=abs(n1-t);if(minabs<=t2)return;}for(int i=0;i<cnt;i++){if((cur==0 || cur==cnta) && num[i]==0) continue;if(!used[i]){int b1,b2;b1=n1;b2=n2;            used[i]=true;if(cur<cnta)n1=n1*10+num[i];elsen2=n2*10+num[i];DFS(cur+1,n);n1=b1;n2=b2;            used[i]=false;}}}int main(){int T;scanf("%d",&T);getchar();while(T--){cnt=0;char ch;while((ch=getchar())!='\n'){            if(ch>='0' && ch<='9')num[cnt++]=ch-'0';}cnta=cnt>>1;cntb=cnt-cnta;minabs=INF;n1=n2=0;memset(used,0,sizeof(used));DFS(0,cnt);if(minabs==INF)printf("%d\n",n1bak);elseprintf("%d\n",minabs);}}


    0 0
    原创粉丝点击