首页 > 代码库 > uva 10344 23 out of 5 (DFS)

uva 10344 23 out of 5 (DFS)

                           uva 10344 23 out of 5


Your task is to write a program that can decide whether you can find an arithmetic expression consisting of five given numbers技术分享(1<=i<=5) that will yield the value 23.
For this problem we will only consider arithmetic expressions of the following from:

技术分享
            
where 技术分享: {1,2,3,4,5} -> {1,2,3,4,5} is a bijective function 
and 技术分享 {+,-,*} (1<=i<=4)     

Input

The Input consists of 5-Tupels of positive Integers, each between 1 and 50.
Input is terminated by a line containing five zero‘s. This line should not be processed.

Output

For each 5-Tupel print "Possible" (without quotes) if their exists an arithmetic expression (as described above) that yields 23. Otherwise print "Impossible".

Sample Input

1 1 1 1 1 
1 2 3 4 5 
2 3 5 7 11 
0 0 0 0 0 

Sample Output

Impossible 
Possible 
Possible 



题目大意:加减乘 23(类似游戏加减乘除24)

解题思路:DFS。


#include<stdio.h>
#include<algorithm>
using namespace std;
int num[6], flag;
void DFS(int cnt, int ans) {
	if (cnt == 5) {
		if (ans == 23) flag = 1;
		return;
	}
	DFS(cnt + 1, ans + num[cnt]);
	DFS(cnt + 1, ans - num[cnt]);
	DFS(cnt + 1, ans * num[cnt]);
}
int main() {
	while (scanf("%d %d %d %d %d", &num[0], &num[1], &num[2], &num[3], &num[4]) == 5) {
		if (num[0] == 0 && num[1] == 0 && num[2] == 0 && num[3] == 0 && num[4] == 0) break;
		flag = 0;
		sort(num, num + 5);
		do { DFS(1, num[0]); } while (next_permutation(num, num + 5));
		if (flag) printf("Possible\n");
		else printf("Impossible\n");
	}
}



uva 10344 23 out of 5 (DFS)