zoukankan      html  css  js  c++  java
  • P1236 算24点

    #include <bits/stdc++.h>
    using namespace std;
    int b[4];
    int a[3];
    int calc(int a, int b, int c) {
    	if(c == 1) return a + b;
    	else if(c == 2) return a - b;
    	else if(c == 3) return a * b;
    	else if(c == 4) {
    		if(a >= b && a % b == 0) return a/b;
    		else return -1;
    	}
    }
    char trans[] = {'0', '+', '-', '*', '/'};
    bool dfs(int cur) {
    	if(cur == 3) {
    		int one = calc(b[0], b[1], a[0]);
    		int two = calc(one, b[2], a[1]);
    		int three = calc(two, b[3], a[2]);
    		if(one != -1 && two!=-1 && three!=-1 && three == 24) return true;
    		else return false;
    	}
    	for(int i = 1; i <= 4; i++) {
    		a[cur] = i;
    		if(dfs(cur+1)) return true;
    	}
    	return false;
    }
    int main(int argc, char const *argv[])
    {
    	
    	cin >> b[0] >> b[1] >> b[2] >> b[3];
    	sort(b, b+4);
    	bool x;
    	do{
    		if(x = dfs(0)) break;
    	} while(next_permutation(b, b+4));
    	if(x) {
    		int one = calc(b[0], b[1], a[0]);
    		int two = calc(one, b[2], a[1]);
    		int three = calc(two, b[3], a[2]);
    		cout << max(b[0], b[1]) << trans[a[0]] << min(b[0], b[1]) << '=' << one << endl;
    		cout << max(one, b[2]) << trans[a[1]] << min(one, b[2]) << '=' << two << endl;
    		cout << max(two, b[3]) << trans[a[2]] << min(two, b[3]) << '=' << three << endl;
    	}
    	else cout << "No answer!";
    	return 0;
    }
    
  • 相关阅读:
    设计模式之简单工厂模式
    设计模式之工厂方法模式
    设计模式之抽象工厂模式
    面向对象设计原则
    Spring与Struts整合
    Spring与Hibernate、Mybatis整合
    Java中执行外部命令
    Spring3之Security
    综合练习:词频统计
    组合数据类型综合练习
  • 原文地址:https://www.cnblogs.com/gengchen/p/6048291.html
Copyright © 2011-2022 走看看