写搜索写晕了
  • 板块P1236 算24点
  • 楼主bckkkk
  • 当前回复0
  • 已保存回复0
  • 发布时间2025/7/22 11:33
  • 上次更新2025/7/22 16:17:03
查看原帖
写搜索写晕了
1397805
bckkkk楼主2025/7/22 11:33
#include <bits/stdc++.h>

using namespace std;
int num[5];
struct node{
	int a,b,ans;
	char x;
};
vector<node> res;
vector<node> path;
bool flag;
bool used[5];
void dfs(int sum){
	if(path.size()>3)return ;
	if(sum==24 && path.size()==3){
		res=path;
		flag=1;
		return ;
	}
	for (int i = 0; i < 4; i ++){
		if(used[i])continue;
		node p;
		p.a=sum,p.b=num[i];
		used[i]=1;
		//+
		p.ans=p.a+p.b,p.x='+';
		path.push_back(p);
		dfs(p.ans);
		path.pop_back();
		//-
		p.ans=p.a-p.b,p.x='-';
		path.push_back(p);
		dfs(p.ans);
		path.pop_back();
		//*
		p.ans=p.a*p.b,p.x='*';
		path.push_back(p);
		dfs(p.ans);
		path.pop_back();
		//%
		if(p.a%p.b==0){
			p.ans=p.a/p.b,p.x='/';
			path.push_back(p);
			dfs(p.ans);
			path.pop_back();
		}
		used[i]=0;
	}
}
int main(){
	
	cin >> num[0]>>num[1]>>num[2]>>num[3];
	for(int i = 0; i < 4; i++){
        memset(used, 0, sizeof used);
        path.clear();
        used[i] = true;
        dfs(num[i]);
        if(flag) break;
    }
	if(flag){
		for(int i =0; i < res.size(); i ++){
			if(res[i].x=='+'||res[i].x=='*'){
				cout << max(res[i].a,res[i].b) <<res[i].x<<min(res[i].a,res[i].b)<<'='<<res[i].ans<<endl;
			}
			else{
				cout << res[i].a <<res[i].x<<res[i].b<<'='<<res[i].ans<<endl;
			}
		}
	}else{
		cout <<"No answer!";
	}
	return 0;
}

90pts,#8测试点WA

提交记录

2025/7/22 11:33
加载中...