UVA10344 23 out 5

本文探讨了如何使用五个数字通过加减乘法操作得到23的方法,包括排序、全排列枚举和递归检查过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

给你5个数字  要求你能随意使用 + - *三个运算符是这五个数的结果为23(每个数只能使用一次)


先排序,再用nenx_premutation函数枚举每一个全排列

对于每一个全排列 通过递归来暴力检查


<pre name="code" class="cpp">#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<string>
using namespace std;
int con[5];
int temp = 0;
bool dfs(int cur,int temp){
	if (cur == 5){
		if (temp == 23)
			return true;
		else return false;
	}

	if (dfs(cur + 1, temp + con[cur])) return true;
	if (dfs(cur + 1, temp * con[cur])) return true;
	if (dfs(cur + 1, temp - con[cur])) return true;
	return false;
}
bool cmp(int a,int b){
	return a < b;
}
int main(){
	while (true){
		int x = 0;
		for (int i = 0; i < 5; i++){
			cin >> con[i];
			x += con[i];
		}
		if (x == 0)
			break;
		bool flag = true;
		sort(con,con+5,cmp);
		for (int i = 0; i < 5; i++)
			cout <<"  "<< con[i];
		cout << endl;
		do{
			if (dfs(1, temp)){
				cout << "Possible" << endl;
				flag = false;
				break;
			}
		} while (next_permutation(con, con + 5));
		if (flag)
			cout << "Impossible" << endl;
	}
	return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值