POJ 2718 Smallest Difference 枚举

时间:2022-03-30 09:00:44

http://poj.org/problem?id=2718

题目大意:

给你一些数字(单个),不会重复出现且从小到大。他们可以组成两个各个位上的数字均不一样的数,如 0, 1, 2, 4, 6 ,7可以组成10 和 2467,但最小的差值由204和176组成,差值为28,这题就是求最小的差值。

思路:

直接枚举即可。

注意不能有前导0,当只有两个数时。。。比如0 和2答案为2,分开讨论就是了。

#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
using namespace std;
const int INF=0x3fffffff;
int a[12],len;
char c;
int solve(int start,int en)
{
int res=0;
for(int j=start;j<en;j++)
{
if(a[start]==0)
return INF;
res=res*10+a[j];
}
return res==0? INF:res;
}
int main()
{
int T;
scanf("%d",&T);
getchar();
while(T--)
{
len=0; while(scanf("%c",&c),c!='\n')
{
if(c==' ') continue;
a[len++]=c-'0';
}
int ans=INF;
if(len==2)
ans=a[1]-a[0];
else
do
{
int x=solve(0,len>>1);
int y=solve(len>>1,len); int t=abs(x-y);
if(t<ans && x!=INF && y!= INF)
ans=t; x=solve(0,(len>>1)+1);
y=solve((len>>1)+1,len); t=abs(x-y);
if(t<ans && x!=INF && y!= INF)
ans=t;
}while(next_permutation(a,a+len)); printf("%d\n",ans);
} return 0;
}