UVa 10344 - 23 out of 5 全排列递归回溯

本文介绍了一个使用next_permutation函数解决特定数学问题的C++程序实例。通过详细的代码解析,展示了如何利用递归和标准库函数next_permutation来寻找五数之组合为23的所有可能情况。文章强调了在使用next_permutation前进行额外递归的重要性。

   一开始无数次WA, 实在不知道错在哪里,最后看了别人代码才发现

    用next_permutation()之前是该数组最下值,但是也要dfs()!!!!!

   也就是说在用next_permutation() 之前还有一次递归!!!!

 

  

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
bool ok;
int num[5];

void dfs(int i, int cur) {
    if(i == 5) {
        if(cur == 23)
            ok = true;
        else
            return ;
    }
    if(ok) { return ;}
    dfs(i + 1, cur + num[i]);
    dfs(i + 1, cur - num[i]);
    dfs(i + 1, cur * num[i]);
}
int main()
{
    //freopen("in.txt", "r", stdin);
    int j;
    bool cut;
    while(true) {
        cut = false;
        for(j = 0; j < 5; j ++) {
            scanf("%d", &num[j]);
            if(num[j])
            cut = true;
        }
        if(!cut) break;
        ok = false;
        sort(num, num + 5);
        dfs(1, num[0]);
        while(!ok && next_permutation(num, num + 5)) {
            dfs(1, num[0]);
        }

        if(ok)
            printf("Possible\n");
        else
            printf("Impossible\n");
    }
    return 0;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值