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;
    }
    
  • 相关阅读:
    android操作数据库
    Android读写SD卡上的文件
    第四章 函数与程序结构
    getchar()与EOF
    NULL, '',0 '0'的区别
    TCPL 行计数
    行计数
    getchar()用法
    在C语言中,double、long、unsigned、int、char类型数据所占字节数
    队列——解密QQ号
  • 原文地址:https://www.cnblogs.com/gengchen/p/6048291.html
Copyright © 2011-2022 走看看