zoukankan      html  css  js  c++  java
  • 洛谷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;
    }
    
  • 相关阅读:
    java基础—GUI编程(一)
    java基础—数组
    java基础—异常处理
    java基础—面向对象
    多线程(二)
    多线程(一)
    ORACLE数据库SQL语句的执行过程
    Jetty直接调试,不用部署,不用弄一些杂七杂八的设置
    (2.1)servlet线程安全问题
    (3)tomcat源代码分析环境的搭建
  • 原文地址:https://www.cnblogs.com/liuwenyao/p/11838303.html
Copyright © 2011-2022 走看看