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

   一开始无数次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;
}


 

你可能感兴趣的:(uva,递归回溯)