例题总结——算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;
}

题目二

·题目内容

 

猜你喜欢

转载自www.cnblogs.com/konglingyi/p/11391035.html