Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 10416 | Accepted: 2845 |
Description
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
Output
Sample Input
1 0 1 2 4 6 7
Sample Output
28
Source
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
#define MAX 0x3f3f3f3f
int a[15];
int ans,n,mid;
void slove()
{
ans=MAX;
sort(a,a+n);
mid=(n+1)/2;
while(a[0]==0)//把排列組合跑到a[0]不爲0的那種,即第一個數x的前導一定不爲0了
{
next_permutation(a,a+n);
}
do
{
if(a[mid]!=0)//如果第二個數的前導也不爲0
{
int x=a[0],y=a[mid];
for(int i=1;i<mid;i++)
{
x=x*10+a[i];
}
for(int i=mid+1;i<n;i++)
{
y=y*10+a[i];
}
if(ans>abs(x-y))
{
ans=abs(x-y);
}
}
}
while(next_permutation(a,a+n));
printf("%d\n",ans);
}
int main()
{
int t;
char c;
scanf("%d",&t);
getchar();//得放到這裏,不能放到while循環內部,否則會出現第二組數據答案不照,不知道什麼原理
while(t--)
{
memset(a,0,sizeof(a));
n=0;
while((c=getchar())!='\n')//新學的輸入,也可以用gets()獲得一個含空格的字符串,掃一遍放入數字數組也行
{
if(c!=' ')
a[n++]=c-'0';
}
if(n==2)
{
ans=abs(a[0]-a[1]);
printf("%d\n",ans);
continue;
}
else
{
slove();
}
}
return 0;
}