洛谷P1236 算24点

题目
直接爆搜,每次将两个可以合并也就是正整数的值合并,然后删去任意一个值。中途需要注意得点是,在dfs中,temp数千万不要开全局变量。还有一点就是因为原题要满足结果输出要先输出大数,后输出小数,但还是尽量少用swap,尤其是在有temp保存值的时候,还是少用swap

#include <bits/stdc++.h>
using namespace std;
struct step{
	int a, b, ans;
	char c;
}sta[10010];
int a[1001], vis[1000], flag;
bool check()
{
	for (int i = 1; i <= 4; i++)
		if (a[i] == 24) return 1;
	return 0;
}
void print()
{	
	for (int i = 1; i <= 3; i++)//一定有三步, 
	{
		if (sta[i].a < sta[i].b) swap(sta[i].a, sta[i].b);
		printf("%d%c%d=%d\n", sta[i].a, sta[i].c, sta[i].b, sta[i].ans);
	}
}
void dfs(int now)
{
	if (now == 4)
	{
		if (check())
			flag = 1, print(), exit(0);
		return;
	}
	int temp1, temp2;
	for (int i = 1; i <= 4; i++)
		for (int j = 1; j <= 4; j++)
		{
			if (i == j || a[i] <= 0 || a[j] <= 0) 
				continue;
			if (a[i] < a[j]) continue;
			//加
			sta[now].a = a[i], sta[now].b = a[j];
			sta[now].c = '+', sta[now].ans = a[i] + a[j];
			temp1 = a[j], temp2 = a[i];
			a[i] = sta[now].ans; 
			a[j] = -1;
			dfs(now + 1);
			a[j] = temp1;
			a[i] = temp2;
			//减
			sta[now].a = a[i], sta[now].b = a[j];
			sta[now].c = '-', sta[now].ans = a[i] - a[j], temp1 = a[j], temp2 = a[i];
			a[i] = sta[now].ans; 
			a[j] = -1;
			dfs(now + 1);
			a[j] = temp1;
			a[i] = temp2;
			//乘
			sta[now].a = a[i], sta[now].b = a[j];
			sta[now].c = '*', sta[now].ans = a[i] * a[j], temp1 = a[j], temp2 = a[i];
			a[i] = sta[now].ans; 
			a[j] = -1;
 			dfs(now + 1);
			a[j] = temp1;
			a[i] = temp2;
			//除
			if (a[j] != 0 && a[i] % a[j] == 0)
			{
				sta[now].a = a[i], sta[now].b = a[j];
				sta[now].c = '/', sta[now].ans = a[i] / a[j], temp1 = a[j], temp2 = a[i];
				a[i] = sta[now].ans;
				a[j] = -1;
				dfs(now + 1);
				a[j] = temp1;
				a[i] = temp2;	
			}
		}
}
int main()
{
	scanf("%d%d%d%d", &a[1], &a[2], &a[3], &a[4]);
	dfs(1); 
	printf("No answer!");
	return 0;
}
posted @ 2019-11-11 20:42  DAGGGGGGGGGGGG  阅读(431)  评论(0编辑  收藏  举报