您的位置:首页 > Web前端

POJ 2718 - Smallest Difference(穷竭搜索)

2014-01-13 12:55 369 查看
Smallest Difference

Time Limit: 1000MSMemory Limit: 65536K
Total Submissions: 3238Accepted: 910
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


===============================

题意:给出的数字可以分开组成许多组,求所有组中的最小差。0不能做第一位

想能得到最小差的话其中一个数的位数一定为n/2,先深搜得到这个数,再把剩下的数字全排列即第二个数,计算差值

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>

using namespace std;
int a[20],b[20],vis[20];
int n,ans;

void solve(int sum1)
{
int num=0;
int sum2=0;
for(int i=0;i<n;i++)
{
if(!vis[i])
{
b[num++]=a[i];
sum2=sum2*10+a[i];
}
}
//cout<<"sum1="<<sum1<<" sum2="<<sum2<<endl;
if((b[0]!=0)||(b[0]==0&&num==1)) ans=min(ans,abs(sum1-sum2));
while(next_permutation(b,b+num))
{
if(b[0]==0) continue;
sum2=0;
for(int i=0;i<num;i++) sum2=sum2*10+b[i];
ans=min(ans,abs(sum1-sum2));
}
//cout<<"sum1="<<sum1<<" sum2="<<sum2<<endl;
}

void dfs(int res,int sum)
{
if(res>n/2)
{
solve(sum);
return;
}
for(int i=0;i<n;i++)
{
if(res==1&&a[i]==0) continue;
//cout<<"i="<<i<<endl;
if(vis[i]) continue;
vis[i]=1;
dfs(res+1,sum*10+a[i]);
vis[i]=0;
}
}

int main()
{
int T;
char str[20];
scanf("%d",&T);
getchar();
while(T--)
{
n=0;ans=1e9;
memset(vis,0,sizeof(vis));
gets(str);
int len=strlen(str);
for(int i=0;i<len;i+=2) a[n++]=str[i]-'0';
//for(int i=0;i<n;i++) cout<<a[i]<<" "; cout<<endl;
dfs(1,0);
printf("%d\n",ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: