题目链接:http://poj.org/problem?id=2718
首先关于输入的问题,因为这道题不像其他题目一样先告诉你输入的数字有多少个,这就需要我们进行一波骚操作。
输入数据的代码:
int a[15];
char ch;
while((ch = getchar()) != '\n')
{
if(ch != ' ')
a[j++] = ch - '0';
}
特别注意的是,因为是多组数据输入,所以我们会用到EOF的东西,在输入数据之前要加入一个语句 getchar(); 来接收掉上面输入进去的回车符,不然的话会失去第一个元素。。亲测有效!!!
然后还用到一个贼牛逼的函数。。为全排列函数。。。next_permutation(数组名称,数组的大小 + 名称)
需要注意的一个点是它枚举的顺序是按照字典序进行枚举(poj3187用这个就很简单了)
使用方法:
do
{
代码片段
}while(next_permutation(数组名称, 数组名称+数组名称加上大小))
eg:
do
{
}while(next_permutation(a, a + j)); //j为我设的a数组的大小
顺便安利一波代码:
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#define INF 0x3f3f3f3f
using namespace std;
int a[15], j, sum1, sum2, res;
char ch;
void fun()
{
res = INF;
while(a[0] == 0)
next_permutation(a, a + j);
do
{
int mid = (j + 1) / 2;
if(a[mid]) //防止a[mid]为0的时候少了一位
{
sum1 = sum2 = 0;
for(int i = 0; i < mid; i++)
sum1 = sum1 * 10 + a[i];
for(int i = mid; i < j; i++)
sum2 = sum2 * 10 + a[i];
if(abs(sum1 - sum2) < res)
res = abs(sum1 - sum2);
}
}while(next_permutation(a, a + j)); //进行全排列
cout << res << endl;
}
int main()
{
int n;
while(cin >> n)
{
getchar();
while(n--)
{
j = 0;
memset(a, 0, sizeof(a));
while((ch = getchar()) != '\n')
{
if(ch != ' ')
a[j++] = ch - '0';
}
if(j == 1)
cout << a[0] << endl;
else
{
if(j == 2)
cout << abs(a[0] - a[1]) << endl;
else
fun();
}
}
}
return 0;
}