24 point game(ACM)

来源:互联网 发布:二战苏联远东部队知乎 编辑:程序博客网 时间:2024/06/11 17:37

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

分析:

本题采用的是普通思路

首先对3 3 8 8得到其全排列,3,3,8,8/3,8,3,8/3,8,8,3/.../8,3,8,3(正确的排列)/...

然后对上面每一种排列计算其可能的值

最后检查所有结果中是否有24,若有输出Yes,否则输出No

代码如下:

#include<iostream>

#include<vector>

using namespace std;

vector<double> getResult(vector<double> &v1)

{

vector<double> result;

if (v1.size() == 1)

{

result.push_back(v1[0]);

return result;

}

vector<double> left;

vector<double> right;

for (int i = 0; i < v1.size() - 1; ++i)

{

vector<double> ld(v1.begin(), v1.begin() + i + 1);

left = getResult(ld);

vector<double> rd(v1.begin() + i + 1, v1.end());

right = getResult(rd);

for (int j = 0; j < left.size(); ++j)

{

for (int k = 0; k < right.size(); ++k)

{

result.push_back(left[j] + right[k]);

result.push_back(left[j] - right[k]);

result.push_back(left[j] * right[k]);

result.push_back(right[k] - left[j]);

result.push_back(left[j] / right[k]);

result.push_back(right[k] / left[j]);

 

}

}

}

return result;

}

int main()

{

int n;

cin >> n;

vector<int> vSum;

vector<vector<int> > v(n);

for (int i = 0; i < n; ++i)

{

int num, sum;

cin >> num >> sum;

vSum.push_back(sum);

for (int j = 0; j < num; ++j)

{

int s;

cin >> s;

v[i].push_back(s);

}

}

for (int i = 0; i < n; ++i)

{

if (v[i].size() == 0)

{

cout << "No" << endl;

continue;

}

bool flag = false;

vector<double> vd(v[i].begin(), v[i].end());

 

vector<double> result = getResult(vd);

for (int j = 0; j < result.size(); ++j)

{

if ((int)result[j] == vSum[i])

{

flag = true;

break;

}

}

if (flag)

cout << "Yes" << endl;

else

cout << "No" << endl;

}

 

}

 

0 0
原创粉丝点击