您的位置:首页 > 其它

第九十八周,搜索24点

2016-05-21 14:01 288 查看
题目链接:http://hihocoder.com/contest/hiho98/problem/1

24点游戏大家都玩过。我算了一下,24点有4!*5*4*4*4种情况。

从这个公式大家就能看出这个题目的思路来。

4!就是这4个数的全排列,5就是加入括号的情况,总共5中,4*4*4就是三个符号的种类。

这里比较有趣的地方是,符号的对应。

#include <stdio.h>
#include <string.h>
#include <math.h>

#include <algorithm>

using namespace std;

const int M=4;

const int EPS=1e-10;

const char oper[]="+-*/";

double a[M];
char p[M];

bool flag;

double add(double x,double y,int index)
{
switch(p[index])
{

case '+':
return x+y;

case '-':
return x-y;

case '*':
return x*y;

case '/':
return x/y;
}
}

bool cal()
{
bool f0=(24==add(add(add(a[0],a[1],0),a[2],1),a[3],2));
bool f1=(24==add(add(a[0],a[1],0),add(a[2],a[3],2),1));
bool f2=(24==add(a[0],add(add(a[1],a[2],1),a[3],2),0));
bool f3=(24==add(a[0],add(a[1],add(a[2],a[3],2),1),0));
bool f4=(24==add(add(a[0],add(a[1],a[2],1),0),a[3],2));
return f0||f1||f2||f3||f4;
}

void dfs(int x)
{
if(x==3)
{
if(cal())
flag=true;
return ;
}

if(flag)
return ;
for(int i=0; i<4; i++)
{
p[x]=oper[i];
dfs(x+1);
if(flag)
return ;
}
}

int main()
{
int N;
for(scanf("%d",&N); N--;)
{
for(int i=0; i<M; i++)
scanf("%lfd",&a[i]);

flag=false;
sort(a,a+4);
do
{
dfs(0);
if(flag)
break;
}
while(next_permutation(a,a+4));

puts(flag? "Yes":"No");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: