随机算法70求助
查看原帖
随机算法70求助
1094030
yr409892525楼主2024/8/11 09:36
#include<bits/stdc++.h>
#define ll long long
using namespace std;
int a[10];
int b[10];
void work(){
	for(int i=1;i<=100;i++){
		for(int j=1;j<=3;j++){
			b[j]=(rand()%4+1);
		}
		int sum=a[1];
		for(int j=1;j<=3;j++){
			if(b[j]==1){
				sum+=a[j+1];
			}
			if(b[j]==2){
				if(sum-a[j+1]<0){
					sum=-1;
					break;
				}
				sum-=a[j+1];
			}
			if(b[j]==3){
				sum*=a[j+1];
			}
			if(b[j]==4){
				if(sum%a[j+1]!=0){
					sum=-1;
					break;
				}
				sum/=a[j+1];
			}
		}
		if(sum==24){
			sum=a[1];
			for(int j=1;j<=3;j++){
				cout<<sum;
				if(b[j]==1){
					sum+=a[j+1];
					cout<<"+";
				}
				if(b[j]==2){
					cout<<"-";
					sum-=a[j+1];
				}
				if(b[j]==3){
					cout<<"*";
					sum*=a[j+1];
				}
				if(b[j]==4){
					cout<<"/";
					sum/=a[j+1];
				}
				cout<<a[j+1]<<"="<<sum<<"\n";
			}
			exit(0);
		}
	}
}
int main(){
	ios::sync_with_stdio(false);
	cin.tie(0);cout.tie(0);
	srand(time(0)); 
	cin>>a[1]>>a[2]>>a[3]>>a[4];
	for(int i=1;i<=1000;i++){
		for(int j=1;j<=(rand()%2+1);j++){
			swap(a[(rand()%4+1)],a[(rand()%3+2)]);
		}
		work();
	}
	cout<<"No answer!\n";
	return 0;
}
2024/8/11 09:36
加载中...