The previous version has a small problem, the parentheses are considered too little, lost a few cases, so the number of brackets is sparse, so I slightly improved, and I followed the teacher's standards to change the format a little bit
Here's my improved code.
#include <iostream>#include<cstdlib>#include<Set>#include<ctime>#include<string.h>#include<string>#include<sstream>using namespacestd;#defineRandom (x) (rand ()%x)inta[ -];Chars[4]={'+','-','*','/'};Charsym[ -];Charbrackets[ -];intnum[ -];stringNumtostring (intnum) {StringStream ss; string as=""; SS<<num; SS>> as; return as;}voidDfsintSintE//using DFS recursion to add parentheses{ if(!random (4))//One-fourth probability of not doing anything { return; } if(e-s<=1)//only one element or no element, no action is made { return; } intS1=random (e-s-1) +s;//randomly generates a position where parentheses are inserted intE1=random (E-S1) +S1; while(s1<s| | e1>e| | s1>=e1| | (s1==s&&e1==e))//Avoid useless parentheses{S1=random (e-s-1) +s;e1=random (E-S1) +S1; } if(brackets[s1]==')'|| brackets[e1]=='(') { return; } BRACKETS[S1]='('; BRACKETS[E1]=')'; NUM[S1]++; NUM[E1]++; DFS (S,S1-1);//insert parentheses to the left of several elementsDFS (e1+1, e);//a few elements between parenthesesDFS (S1,E1);//several elements to the right of the parentheses}intMain () {Srand (Time (NULL)); intt= -nn; Set<string>MySet; stringans; while(t--) {ans=""; N=random (8)+2; memset (brackets,'.',sizeof(brackets)); memset (num,0,sizeof(num)); for(intI=1; i<=n;i++) {A[i]= Random (999)+1; Sym[i]=s[random (4)]; } DFS (1, N); while(brackets[1]=='('&&num[1]--) {ans+='('; } ans+=numtostring (a[1]); for(intI=2; i<=n;i++) {ans+=Sym[i]; while(brackets[i]=='('&&num[i]--) {ans+='('; } ans+=numtostring (A[i]); while(brackets[i]==')'&&num[i]--) {ans+=')'; } } if(!myset.count (ANS)) {cout<<ans<<Endl; Myset.insert (ANS); } Else{T++; } } return 0;}
Random Arithmetic of 10 operands (two)