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

NYOJ43 24 Point game 【回溯】

时间:2014-06-04 21:06:57      阅读:295      评论:0      收藏:0      [点我收藏+]

标签:nyoj43

24 Point game

时间限制:3000 ms  |  内存限制:65535 KB
难度:5
描述

There is a game which is called 24 Point game.

In this game , you will be given some numbers. Your task is to find an expression which have all the given numbers and the value of the expression should be 24 .The expression mustn‘t have any other operator except plus,minus,multiply,divide and the brackets. 

e.g. If the numbers you are given is "3 3 8 8", you can give "8/(3-8/3)" as an answer. All the numbers should be used and the bracktes can be nested. 

Your task in this problem is only to judge whether the given numbers can be used to find a expression whose value is the given number。

输入
The input has multicases and each case contains one line
The first line of the input is an non-negative integer C(C<=100),which indicates the number of the cases.
Each line has some integers,the first integer M(0<=M<=5) is the total number of the given numbers to consist the expression,the second integers N(0<=N<=100) is the number which the value of the expression should be.
Then,the followed M integer is the given numbers. All the given numbers is non-negative and less than 100
输出
For each test-cases,output "Yes" if there is an expression which fit all the demands,otherwise output "No" instead.
样例输入
2
4 24 3 3 8 8
3 24 8 3 3
样例输出
Yes
No

这题的思路是把n个数字任意两两按照+-*/组合,直到只剩一个数时与目标数比较是否相等即可,开始因为cal函数的返回值写成了int而WA了一次,很亏,以后要注意。

#include <stdio.h>
#include <math.h>
int t, n;
double targ, arr[10];
bool vis[10];

double cal(double a, double b, int k){
	switch(k){
		case 0: return a + b;
		case 1: return a - b;
		case 2: return a * b;
		case 3: return a / b;
		case 4: return b - a;
		case 5: return b / a;
	}
}

bool backTrack(int num, int pos){
	if(num == 1 && fabs(arr[pos] - targ) < 1e-5) return true;
	double tmp1, tmp2;
	
	for(int i = 0; i < n; ++i){
		if(!vis[i]) for(int j = i + 1; j < n; ++j){
			if(!vis[j]){
				tmp1 = arr[i]; tmp2 = arr[j];
				for(int k = 0; k < 6; ++k){
					if(k == 3 && arr[j] == 0 || k == 5 && arr[i] == 0) continue;
					arr[j] = cal(arr[i], arr[j], k);
					vis[i] = true;
					if(backTrack(num - 1, j)) return true;
					vis[i] = false;
					arr[i] = tmp1; arr[j] = tmp2;
				}
			}
		}
	}
	return false;
}

int main(){
	scanf("%d", &t);
	while(t--){
		scanf("%d%lf", &n, &targ);
		for(int i = 0; i < n; ++i)
			scanf("%lf", &arr[i]);
		for(int i = 0; i < 10; ++i) vis[i] = false;
		printf(backTrack(n, n - 1) ? "Yes\n" : "No\n"); //n个元素,结束位置是n-1
	}
	return 0;
}


NYOJ43 24 Point game 【回溯】,布布扣,bubuko.com

NYOJ43 24 Point game 【回溯】

标签:nyoj43

原文地址:http://blog.csdn.net/chang_mu/article/details/27217365

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