现在的位置: 首页 > 综合 > 正文

POJ 2718 Smallest Difference

2018年04月28日 ⁄ 综合 ⁄ 共 2208字 ⁄ 字号 评论关闭
Smallest Difference
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 4688   Accepted: 1303

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

解题思路:
这道题是挑战上面的题目,被分到了穷尽搜索里面了,题目的大意就是说给你一串数字,你把他们按照要求分成两个数字,
然后求出这两个数字的差的最小值,注意不能有前导0的出现,最先想到的应该是无穷枚举了,只要拼命的枚举就好,但是,···
代码:
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<iostream>
using namespace std;
const int inf=1<<29;
int num[20],cnt,cnta,cntb,val,ans;
int nums[10]={1,10,100,1000,10000,100000,1000000};
bool usea[20],useb[20];
char ch;
void DFS_B(int vals,int deep)
{
    if(deep>0&&abs(val-vals*nums[cntb-deep])>=ans)
	return;
    if(deep==cntb)
    {
	ans=min(ans,max(val,vals)-min(val,vals));
	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);
	return;
    }
    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;
}

抱歉!评论已关闭.