例题总结——算24点

题目一

·题目内容

1.Background
CZR很喜欢学数学,但是他数学一直不好,所以他决定玩24点来练习
自己.
2.Description
然而由于他数学不好,所以他只会加减法:
给定四个数,请问是否能通过加法和减法来得到24.
为了训练自己,他每次都会进行524点游戏
·题目来源:山东集训考试题二第二题

·算法:暴力/dfs

·太简单了(连我这样蒟蒻都觉得太弱了),就不介绍了,免得浪费大佬的心神

·板子一:【暴力】 

#include <cstdio>

using namespace std;

int main() {
	//freopen("24.in", "r", stdin);
	//freopen("24.out", "w", stdout);
	int p[5][2];
	int tmp;
	int a[5];
	
	p[1][0] = p[2][0] = p[3][0] = p[4][0] = -1;
	p[1][1] = p[2][1] = p[3][1] = p[4][1] = 1;
	
	for (int T = 1; T <= 5; ++T) {
		for (int i = 1; i <= 4; ++i)
			scanf("%d", a + i);
		for (int p1 = 0; p1 <= 1; ++p1)
		for (int p2 = 0; p2 <= 1; ++p2)
		for (int p3 = 0; p3 <= 1; ++p3)
		for (int p4 = 0; p4 <= 1; ++p4)	{
			tmp = p[1][p1] * a[1] + p[2][p2] * a[2] + p[3][p3] * a[3] + p[4][p4] * a[4];
			if (tmp == 24) {
				puts("Yes.");
				goto end;
			}
		}
		puts("No.");
		end: ;
	}
	//fclose(stdin);
	//fclose(stdout);
	return 0;
}

板子二:【dfs】

#include<iostream>
#include<cstdio>
using namespace std;
int x[5];
bool flag=false;
void search(int a,int index,int ans)
{
    if(index==4&&ans==24) flag=true;
	if(index>4) return ;
	search(x[index+1],index+1,ans+a);
	search(-x[index+1],index+1,ans+a);
 } 
int main()
{
	//freoepn("24.in","r",stdin);
	//freopen("24.out","w",stdout);
	for(int i=1;i<=5;i++)
	{
		flag=false;
		cin>>x[1]>>x[2]>>x[3]>>x[4];
		search(x[1],1,0);
		search(-x[1],1,0);
		if(flag) cout<<"Yes."<<endl;
		else cout<<"No."<<endl;
	} 
	//fclose(stdin);
	//fclose(stdout); 
	return 0;
}

题目二

·题目内容

 

转载于:https://www.cnblogs.com/konglingyi/p/11391035.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值