码迷,mamicode.com
首页 > 其他好文 > 详细

uva 10344 23 out of 5 (DFS)

时间:2015-01-29 14:45:06      阅读:154      评论:0      收藏:0      [点我收藏+]

标签:uva   c语言   

                           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)

标签:uva   c语言   

原文地址:http://blog.csdn.net/llx523113241/article/details/43269319

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!