天天看點

MOOC程式設計與算法練習題——遞歸#2787算24

樣例輸入

5 5 5 1

1 1 4 2

0 0 0 0

樣例輸出

YES

NO

#include <iostream>
#include <cmath>
#define EPS 1e-6
using namespace std;
double a[5];
bool isZero(double x){
	if(fabs(x) <= EPS)
		return true;
	else
		return false;
}
bool count(double a[],int n){
	if(n == 1){//遞歸出口
		if(isZero(a[0] - 24))
			return true;
		else
			return false;
	}
	double b[5];
	for(int i = 0;i < n-1; ++i){
		for(int j = i + 1;j < n; ++j){
			int m = 0;
			for(int k = 0;k < n; ++k){
				if(k != i && k != j)
					b[m++] = a[k];
			}
			b[m] = a[i] + a[j];
			if(count(b,m+1))
				return true;
			b[m] = a[i] - a[j];
			if(count(b,m+1))
				return true;
			b[m] = a[j] - a[i];
			if(count(b,m+1))
				return true;
			b[m] = a[i] * a[j];
			if(count(b,m+1))
				return true;
			if(!isZero(a[j])){
				b[m] = a[i] / a[j];
				if(count(b,m+1))
					return true;
			}
			if(!isZero(a[i])){
				b[m] = a[j] / a[i];
				if(count(b,m+1))
					return true;
			}
		}
	}
	return false;
}
int main(){
	while(true){
		for(int i = 0;i < 4; ++i)
			cin >> a[i];
		if(a[0] == 0)
			break;
		if(count(a,4))
			cout << "YES" << endl;
		else
			cout << "NO" << endl;
	}
	return 0;
}