UVa 10344 - 23 out of 5

题目链接:UVa 10344 - 23 out of 5

回溯 + 求下一个排列

#include <iostream>
#include <algorithm>

using namespace std;

int num[5];
bool flag;

void dfs(int cur,int sum)
{
    if(cur == 5)
    {
        if(sum == 23)
            flag = true;
    }
    else
    {
        dfs(cur + 1,sum + num[cur]);
        dfs(cur + 1,sum * num[cur]);
        dfs(cur + 1,sum - num[cur]);
    }
}
int main()
{
    while(cin >> num[0] >> num[1] >> num[2] >> num[3] >> num[4],
          num[0] + num[1] + num[2] + num[3] + num[4])
    {
        flag = false;
        sort(num,num + 5);
        do
            dfs(1,num[0]);
        while(next_permutation(num,num + 5) && !flag);
        if(flag)
            cout<<"Possible"<<endl;
        else
            cout<<"Impossible"<<endl;
    }
    return 0;
}


你可能感兴趣的:(UVa 10344 - 23 out of 5)