您的位置:首页 > Web前端

Smallest Difference (dfs)深度搜索

2017-07-24 19:09 501 查看
Smallest Difference

Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 12001 Accepted: 3261
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

Source

Rocky Mountain 2005

首先呢,这一串数字,要用字符串输入,在转换成数字存入数组;将数组排升序,

之后呢 我们c++的头文件algorithm里有一个全排列的函数,其实可以用dfs写出来数的全排列;

对于每一种全排列都取前n/2个数存入一个数s1中,后面的存入s2中(注意开头有零的可以跳过)

最后 求s1-s2绝对值的最小值;

这题还有以下思路   比如说有 7个数  此时可以将最小的4个数来组成最小的四位数s1,拿最大的3个数组成最大的3位数s2;

求s1-s2即可

比如说8个数  第一次 s1选个最小的非零数,s2选次非零数,有0的话,第二次s2选0,之后s1要先选大的组成一个大的数(不会比s2大) s2选最小的数,直到它们的位数为4 位置  求s2-s1即可

这种思路大家可以自己揣摩揣摩写一写,我还是给的第一种思路的代码

#include <iostream>
#include <cstdio>
#include <algorithm>
#include<string.h>

using namespace std;
int a[20];//存入数 
int main()
{
    int t;
    cin>>t;
    getchar();
    while(t--)
    {
        int k=0,i;
        char s[30];
        gets(s);//接受字符串 
        int l=strlen(s);
        //将字符串变数字存入数组 
        for(i=0;i<l; i+=2)
        {
            a[k++]=s[i]-'0';
        }
        //排序 
        sort(a,a+k);
        int ans,mi=10000000;
        //对全排列进行分割总会找到最小的那个 
        do
        {
            int s1=0,s2=0;
            if((a[0]==0)||(a[k/2]==0&&k>2))
                continue;
            for(int i=0;i<k/2;i++)
                s1=s1*10+a[i];
            for(int j=k/2;j<k;j++)
                s2=s2*10+a[j];
            ans=abs(s1-s2);
            mi=min(ans,mi);
        }
        while(next_permutation(a,a+k));
        cout<<mi<<endl;
    }
    return 0;
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息