这一题,本来也挺简单的。只是用一个深度搜索做一个全排列,然后计算找出使两数差值最小的全排列。后来按照以前的方式写了一个全排列,交上去,告诉我TLE,这让在下很纠结啊。因为如果只是全排列的话,一共需要计算10!次,也就是说,不会超时。后来发现,自己以前写的算法有问题,在搜索的时候,会出现很多冗余的操作,使搜索的效率大大退化。后来更改了数据的处理方式,将算法复杂度降到了10!,然后提交,返回Accepted,不过运行时间大概是500+ms,效率感觉还是有点低了。想起了STL里面的全排列函数,next_permutation(),嗯,我还不会用,以后有空去查查。应该能把时间降到300ms吧。不过网上也有好多人用贪心做的,自己也能想个大概贪心思路,等有空试着写个贪心,看能不能A吧。下面上代码:
#include <cstdio>
#include <cmath>
#include <cstring>
#include <algorithm>
using namespace std;
int ans,hash[20],a[20],n;
int dfs(int step)
{
int i,j,k,tmp,t1,t2;
if(step==n)
{
t1=0; t2=0;
for(i=0,k=1;i<n/2;i++,k*=10)
t1+=k*a[i];
for(i=n/2,k=1;i<n;i++,k*=10)
t2+=k*a[i];
if(t1-t2>0)
t1=t1-t2;
else
t1=t2-t1;
if(ans>t1)
ans=t1;
return 0;
}
for(i=step;i<n;i++)
{
if(n>3&&(step==n/2-1||step==n-1)&&a[i]==0)
continue;
if(n==3&&step==2&&a[i]==0)
continue;
swap(a[step],a[i]);
dfs(step+1);
swap(a[step],a[i]);
}
}
int main()
{
int i,j,k,T;
scanf("%d ",&T);
while(T--)
{
char ch;
n=0;
while((ch=getchar())!='\n')
{
if(ch==' ')
continue;
else
a[n++]=ch-'0';
}
ans=32767;
dfs(0);
printf("%d\n",ans);
}
return 0;
}