POJ 2718 Smallest Difference(dfs 全排列)


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


这道题就把所有给出的数全排列,然后把数字划分为数量靠近的两堆,数量要么都一样,要么后面一堆比前面一堆少一个,然后两堆中的数字按照顺序组成数,绝对值不断更新最小值。要让difference最小,那么一定是数字划分成两堆的时候数量也要靠近。这样划分方法加上全排列,可以确保把所有的情况都考虑进去了。注意0不能为数字之首,但是要特判一下只有两个数的情况。

STL中有全排列函数可以方便地适用,格式参照程序。加上头文件#include<algorithm>

读入的时候也要注意。


#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
#include<cmath>
#include<cstdlib>
#define N 20
#define INF 0x3f3f3f3f
using namespace std;
int a[N];
int num(int x, int y)
{
    int s = 0;
    for (int i = x; i < y; i++) s = s * 10 + a[i];
    return s;
}
int main()
{
    int n, cnt, min_m, m, k;
    char ch;
    scanf("%d", &n);
    getchar();
    while (n--)
    {
        min_m = INF;
        cnt = 0;
        while ((ch = getchar()) != '\n')
        {
            if (ch == ' ') continue;
            a[cnt++] = ch - '0';
        }
        if (cnt == 2)
        {
            min_m = abs(a[0] - a[1]);
            printf("%d\n", min_m);
            continue;
        }
        k = cnt/2;
        do
        {
            if (a[0] == 0 || a[k] == 0) continue;
            min_m = min(min_m, abs(num(0, k) - num(k, cnt)));
        }while(next_permutation(a, a+cnt));
        printf("%d\n", min_m);
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值