POJ 2718 Smallest Difference(全排列)

题意:将n个数字分成两组,两组分别组成一个数字,问两个数字的最小差值。要求,当组内数字个数多于1个时,组成的数字不允许有前导0。(2<=n<=10,每个数字范围是0~9)

分析:

1、枚举n个数字的全排列。

2、当两组数字个数相同或只差1时组成的两个数字才可能出现最小差值。

3、0~cnt/2 - 1为前半组数字,cnt/2~cnt-1为后半组数字。

4、注意getchar()的位置。

#pragma comment(linker, "/STACK:102400000, 102400000")
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cctype>
#include<cmath>
#include<iostream>
#include<sstream>
#include<iterator>
#include<algorithm>
#include<string>
#include<vector>
#include<set>
#include<map>
#include<stack>
#include<deque>
#include<queue>
#include<list>
#define Min(a, b) ((a < b) ? a : b)
#define Max(a, b) ((a < b) ? b : a)
const double eps = 1e-8;
inline int dcmp(double a, double b){
    if(fabs(a - b) < eps) return 0;
    return a > b ? 1 : -1;
}
typedef long long LL;
typedef unsigned long long ULL;
const int INT_INF = 0x3f3f3f3f;
const int INT_M_INF = 0x7f7f7f7f;
const LL LL_INF = 0x3f3f3f3f3f3f3f3f;
const LL LL_M_INF = 0x7f7f7f7f7f7f7f7f;
const int dr[] = {0, 0, -1, 1, -1, -1, 1, 1};
const int dc[] = {-1, 1, 0, 0, -1, 1, -1, 1};
const int MOD = 1e9 + 7;
const double pi = acos(-1.0);
const int MAXN = 10 + 10;
const int MAXT = 10000 + 10;
using namespace std;
int a[MAXN];
string s;
int cnt;
bool judge(){
    if(a[0] == 0 && cnt / 2 - 0 > 1) return false;//前半组数字个数大于1
    if(a[cnt / 2] == 0 && cnt - cnt / 2 > 1) return false;//后半组数字个数大于1
    return true;
}
int main(){
    int T;
    scanf("%d", &T);
    getchar();
    while(T--){
        getline(cin, s);
        stringstream ss(s);
        int x;
        cnt = 0;
        while(ss >> x){
            a[cnt++] = x;
        }
        sort(a, a + cnt);
        int ans = INT_INF;
        do{
            int sum1 = 0, sum2 = 0;
            if(!judge()) continue;
            for(int i = 0; i < cnt / 2; ++i){
                sum1 = sum1 * 10 + a[i];
            }
            for(int i = cnt / 2; i < cnt; ++i){
                sum2 = sum2 * 10 + a[i];
            }
            ans = Min(ans, abs(sum1 - sum2));
        }while(next_permutation(a, a + cnt));
        printf("%d\n", ans);
    }
    return 0;
}

  

原文地址:https://www.cnblogs.com/tyty-Somnuspoppy/p/6512346.html