【POJ】2718 - Smallest Difference(枚举全排列)

本文介绍了一道算法题目,通过枚举全排列的方法来寻找最优解。具体实现上,利用C++语言进行编程,并详细展示了如何遍历所有可能的组合以找到两个分割后的数字之间的最小差值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

点击打开题目


这里写图片描述


题解:枚举全排列,按照固定的分割线分割数字,然后依次更新结果。


代码如下:

#include<cstdio>
#include<algorithm>
#include<iostream>
using namespace std;
int main()
{
    int u;
    int num[15];
    char ch;
    int n,half;
    scanf ("%d",&u);
    int ans;
    while (u--)
    {
        n = 0;
        ans = 0x3f3f3f3f;
        while (scanf ("%d%c",&num[++n],&ch) && ch != '\n');
        if (n == 10)
        {
            cout << 247 << endl;
            continue;
        }
        else if (n == 2)
        {
            cout << num[2] - num[1] << endl;
            continue;
        }
        int a,b;
        half = n >> 1;
        do
        {
            if (num[1] == 0 || num[half+1] == 0)
                continue;
            int pos = 1;
            a = b = 0;
            for ( ; pos <= half ; pos++)
                a = a*10 + num[pos];
            for ( ; pos <= n ; pos++)
                b = b*10 + num[pos];
            ans = min(ans , abs(a-b));
//          if (abs(a-b) < ans)
//          {
//              ans = abs(a-b);
//              cout << "===" << a << ' ' << b << "===" << endl; 
//          }
        }while (next_permutation(num+1,num+1+n));
        cout << ans << endl;
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值