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;
}

posted on 2016-11-09 20:07  蒟蒻konjac  阅读(526)  评论(0编辑  收藏  举报