POj-2718 Smallest Difference--全排列next_permutation()的应用文章标题

next_permutation(s.begin(),s.end())列出下一个较大的组合
prev_permutation(s.begin(),s.end())列出上一个较小的组合

#include<stdio.h>
#include<algorithm>
#include<cmath>
using namespace std;
int main() {
    char the_char_string[100];
    int the_digit_string[13];
    int the_num;
    scanf("%d", &the_num);
    getchar();
    while (the_num--) {
        gets_s(the_char_string);
        int len = 0;
        int min_abs = 100000000;

        for (int i = 0; i<strlen(the_char_string); i++) {
            if ('0'<=the_char_string[i]&&the_char_string[i]<='9') {
                the_digit_string[len++] = the_char_string[i] - '0';
            }
        }
        sort(the_digit_string, the_digit_string + len);

        do {
            if (the_digit_string[0] == 0) {
                continue;
            }
            else if (the_digit_string[len / 2] == 0&&len>2) {
                //处理前面的数字多一个的情况,此时后面的数字串不能以0开头
                int num1 = 0, num2 = 0;
                for (int i = 0; i < len / 2 + 1; i++)
                    num1 = num1 * 10 + the_digit_string[i];
                for (int i = len / 2 + 1; i < len; i++)
                    num2 = num2 * 10 + the_digit_string[i];
                min_abs = min(min_abs, abs(num1 - num2));
            }
            else {
                //处理后面与前面一样或后面的比前面多一个的情况
                int num1 = 0, num2 = 0;
                for (int i = 0; i < len / 2; i++)
                    num1 = num1 * 10 + the_digit_string[i];
                for (int i = len / 2; i < len; i++)
                    num2 = num2 * 10 + the_digit_string[i];
                min_abs = min(min_abs, abs(num1 - num2));
            }
        } while (next_permutation(the_digit_string, the_digit_string + len));
        printf("%d\n", min_abs);
    }
    return 0;
}

O(∩_∩)O谢谢阅读!!!

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值