The main idea is to give a molecular formula containing only four letters of c/h/o/n, to find molecular weight. It would be nice to follow the meaning of the title to simulate. The key and difficult point is how to deal with the number of digits above the letter. The writing was slightly complicated.
#include <iostream>#include<string>#include<cstdio>#include<cstring>#defineMAXN 1000000+10#include<ctype.h>using namespacestd;Doublemol[4] = {12.01,1.008,16.00,14.01} ;///C6h5oh///CO2///C12 H22 O11intMain () {intT; Std::cin>>T; while(T-- ){ stringstr; CIN>>str; intLen =str.size (); DoubleNum_c =0, Num_h =0, Num_o =0, Num_n =0 ; for(inti =0; i < Len; i + + ){ if(I < len-1 ){ if(Isalpha (Str[i])) {if(Str[i] = ='C'&&!isdigit (str[i+1])) Num_c + + ; Else if(Str[i] = ='C'&& IsDigit (str[i+1]) ) { DoubleTemp_c =0 ; intj = i+1 ; while(IsDigit (Str[j])) {Temp_c= temp_c*Ten+ (str[j]-'0') ; J++ ; } num_c+=Temp_c; } if(Str[i] = ='H'&&!isdigit (str[i+1])) Num_h + + ; Else if(Str[i] = ='H'&& IsDigit (str[i+1]) ) { DoubleTemp_h =0 ; intj = i+1 ; while(IsDigit (Str[j])) {Temp_h= temp_h*Ten+ (str[j]-'0') ; J++ ; } num_h+=Temp_h; } if(Str[i] = ='O'&&!isdigit (str[i+1])) Num_o + + ; Else if(Str[i] = ='O'&& IsDigit (str[i+1]) ) { DoubleTemp_o =0 ; intj = i+1 ; while(IsDigit (Str[j])) {Temp_o= temp_o*Ten+ (str[j]-'0') ; J++ ; } num_o+=Temp_o; } if(Str[i] = ='N'&&!isdigit (str[i+1])) Num_n + + ; Else if(Str[i] = ='N'&& IsDigit (str[i+1]) ) { DoubleTemp_n =0 ; intj = i+1 ; while(IsDigit (Str[j])) {Temp_n= temp_n*Ten+ (str[j]-'0') ; J++ ; } num_n+=Temp_n; } } } Else{ if(Str[i] = ='C') Num_c + + ; if(Str[i] = ='H') Num_h + + ; if(Str[i] = ='O') Num_o + + ; if(Str[i] = ='N') Num_n + + ; } }//cout << num_c << "<< num_h <<" << num_o << "<< num_n <&L T Endl; DoubleAns = num_c*mol[0] + num_h*mol[1] + num_o*mol[2] + num_n*mol[3] ; printf ("%.3lf\n", ans); } return 0 ;}
UVA 1586 Molar Mass (c + +) (string processing) (analog)