• 洛谷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
    ", 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;
    }
    
  • 相关阅读:
    go语言xrom使用
    go语言算法
    go语言递归
    go语言map(字典)
    GO语言实现小技巧
    偶遇递归树
    Python中字典对象根据字典某一个key和values去重
    python中将字符串格式转字典
    Azure媒体服务的Apple FairPlay流功能正式上线
    SVG裁剪和平移的顺序
  • 原文地址:https://www.cnblogs.com/liuwenyao/p/11838303.html
Copyright © 2020-2023  润新知