Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <stdlib.h>
- #include <string>
- using namespace std;
- int sampleSize = 0;
- int sample[100];
- int ticketSize = 0;
- int ticket[100];
- int ansSize = 0;
- int N;
- void push(int m[],int &n,int v){
- m[n]=v;
- n++;
- }
- bool has_only_digits(const string s){
- return s.find_first_not_of( "0123456789" ) == string::npos;
- }
- bool validate(string s)
- {
- if(s.size()!=6)return false;
- if(s[0]=='0') return false;
- ticketSize = 0;
- for(int i=0; i<s.size(); ++i)
- {
- if(s[i] - '0' > 9 || s[i] - '0' <0 ) return false;
- push(ticket,ticketSize,s[i] - '0');
- }
- return true;
- }
- int calculator(string s)
- {
- s.push_back('+');
- int stnumber[100];
- int stnumberSize = 0;
- int stbin[100];
- int stbinSize = 0;
- for(int i=0; i<s.size(); ++i)
- {
- if(s[i] != '+' && s[i] != '-'&& s[i] != '*' )
- {
- int n=s[i] - '0';
- while(i+1<s.size() && s[i+1] != '+' && s[i+1] != '-'&& s[i+1] != '*')
- {
- n*=10;
- n+=s[i+1]-'0';
- ++i;
- }
- push(stnumber,stnumberSize,n);
- continue;
- }
- if(stbinSize !=0 &&( (stbin[stbinSize-1] == '*' && s[i] != '*') || (stbin[stbinSize-1] != '*' && s[i] != '*') )){
- while(stnumberSize != 1){
- int a = stnumber[stnumberSize-1] ;
- stnumberSize--;
- int b = stnumber[stnumberSize-1];
- stnumberSize--;
- switch(stbin[stbinSize-1]){
- case '-' : push(stnumber,stnumberSize,-a+b) ;break;
- case '+' : push(stnumber,stnumberSize,a+b);break;
- case '*' : push(stnumber,stnumberSize,a*b);break;
- }
- stbinSize--;
- }}
- push(stbin,stbinSize,s[i]);
- }
- return stnumber[stnumberSize-1];
- }
- void checkSample()
- {
- string a;
- for(int i=0; i<6; ++i)
- {
- a.push_back(ticket[i]+'0');
- if(sample[i] == 1)
- {
- a.push_back('+');
- }
- if(sample[i] == 2)
- {
- a.push_back('-');
- }
- if(sample[i] == 3)
- {
- a.push_back('*');
- }
- }
- if(calculator(a) == N){
- ansSize++;
- cout<<a<<"="<<N<<endl;
- }
- }
- void dfs()
- {
- if(sampleSize == 5)
- {
- checkSample();
- return ;
- }
- push(sample,sampleSize,0);
- dfs();
- sampleSize--;
- push(sample,sampleSize,1);
- dfs();
- sampleSize--;
- push(sample,sampleSize,2);
- dfs();
- sampleSize--;
- push(sample,sampleSize,3);
- dfs();
- sampleSize--;
- }
- int main()
- {
- setlocale(LC_ALL,"Russian");
- string s ;
- while(true){
- ansSize = 0;
- cout<<"Введите шестизначное число:";
- cin>>s;
- if(!validate(s)){
- cout<<"Некорректный ввод"<<endl;
- continue;
- }
- string s2;
- cout<<"Введите N:";
- cin>>s2;
- while(!has_only_digits(s2)){
- cout<<"Некорректный ввод"<<endl;
- cout<<"Введите N:";
- cin>>s2;
- }
- N = atoi( s2.c_str());
- dfs();
- if(ansSize == 0){
- cout<<"Решение не существует."<<endl;
- continue;
- }
- cout<<"Найдено "<<ansSize<<" решений."<<endl;
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement