题解
2025-03-31 14:35:19
发布于:北京
41阅读
0回复
0点赞
大模拟。
首先需要确定 个数的运算顺序。可以使用 枚举全排列。
三个运算符直接使用三重循环来枚举: 代表 , 代表 , 代表 , 代表 .
设 表示 进行 运算符所代表的操作。
运算无非这 种:
F(F(F(a[0],i,a[1]),j,a[2]),k,a[3])
F(F(a[0],i,a[1]),j,F(a[2],k,a[3]))
F(F(a[0],i,F(a[1],j,a[2])),k,a[3])
F(a[0],i,F(F(a[1],j,a[2]),k,a[3]))
F(a[0],i,F(a[1],j,F(a[2],k,a[3])))
字符串输出按照这个写就好。
时间复杂度:,其中 是常数,不超过 .
Code:
#include<bits/stdc++.h>
using namespace std;
#define ll long long
ll _,res;
bool can;
string s;
ll a[4];
char ops[4]={'+','-','*','/'};
inline ll F(const ll &x,const ll &op,const ll &y){
if(x<-1e9||y<-1e9) return -1e18;
if(op==0) return x+y;
if(op==1) return x-y;
if(op==2) return x*y;
if(y==0||x%y) return -1e18;
return x/y;
}
inline bool check(const ll &x){return x>=0&&x%24==0;}
inline void OUT(const string &s){
can=true;
cout<<s<<'\n';
return;
}
int main(){
cin>>_;
while(_--){
can=false;
for(ll i=0;i<4;i++) cin>>a[i];
sort(a,a+4);
do{
for(ll i=0;i<4;i++){
for(ll j=0;j<4;j++){
for(ll k=0;k<4;k++){
res=F(F(F(a[0],i,a[1]),j,a[2]),k,a[3]);
if(check(res)){
s="(("+to_string(a[0])+ops[i]+to_string(a[1])+")"+ops[j]+to_string(a[2])+")"+ops[k]+to_string(a[3]);
OUT(s);
break;
}
res=F(F(a[0],i,a[1]),j,F(a[2],k,a[3]));
if(check(res)){
s="("+to_string(a[0])+ops[i]+to_string(a[1])+")"+ops[j]+"("+to_string(a[2])+ops[k]+to_string(a[3])+")";
OUT(s);
break;
}
res=F(F(a[0],i,F(a[1],j,a[2])),k,a[3]);
if(check(res)){
s="("+to_string(a[0])+ops[i]+"("+to_string(a[1])+ops[j]+to_string(a[2])+"))"+ops[k]+to_string(a[3]);
OUT(s);
break;
}
res=F(a[0],i,F(F(a[1],j,a[2]),k,a[3]));
if(check(res)){
s=to_string(a[0])+ops[i]+"(("+to_string(a[1])+ops[j]+to_string(a[2])+")"+ops[k]+to_string(a[3])+")";
OUT(s);
break;
}
res=F(a[0],i,F(a[1],j,F(a[2],k,a[3])));
if(check(res)){
s=to_string(a[0])+ops[i]+"("+to_string(a[1])+ops[j]+"("+to_string(a[2])+ops[k]+to_string(a[3])+"))";
OUT(s);
break;
}
}
if(can) break;
}
if(can) break;
}
}while(!can&&next_permutation(a,a+4));
if(!can) cout<<"Impossible\n";
}
return 0;
}
这里空空如也
有帮助,赞一个