数组练习题。求解分子量的
这道题让人想起了河南省赛,改进啊…然而这题2007年就有了…
题目解法参考hdu1274 【输出3(ab2(cd))->>abcdcdabcdcdabcdcd】网上大神的解法写了该题。链接和题解在最后
这道题没有括号,每个英文后面或许没有,或许为数字。先判断字母,然后判断应该是几个
题目太长,题目网址:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=4461
Input
Your program is to read from standard input. The input consists of T test cases. The number of test
cases T is given in the first line of the input. Each test case is given in a single line, which contains
a molecular formula as a string. The chemical symbol is given by a capital letter and the length of
the string is greater than 0 and less than 80. The quantity number n which is represented after the
chemical symbol would be omitted when the number is 1 (2 ≤ n ≤ 99).
Output
Your program is to write to standard output. Print exactly one line for each test case. The line should
contain the molar mass of the given molecular formula.
Sample Input
4
C
C6H5OH
NH2CH2COOH
C12H22O11
Sample Output
12.010
94.108
75.070
342.296
#include <stdio.h> #include <ctype.h> #include <string.h> #include <iostream> using namespace std; char s[82]; double sum=0; char ch='\0'; int len; int fun(int ith){ int k; double num; char c; sum=0; len=strlen(s); for(c=s[ith];ith<len;){ if(isalpha(c)){ ch=c; switch(ch){ case 'C': num=12.01;break; case 'H': num=1.008;break; case 'O': num=16.00;break; case 'N': num=14.01;break; default : num=0; } } for(k=0,c=s[++ith];isdigit(c);c=s[++ith]){ k=k*10+c-'0'; } if(!k) k=1; sum+=num*k; if(ith==len) { printf("%.3lf\n",sum); return 1; } } } int main(){ int n,len; freopen("UVa1586.txt","r",stdin); scanf("%d",&n); // cout<<"n="<<n<<endl; while(n--){ sum=0; scanf("%s",s); // cout<<"len="<<len<<endl; fun(0); } return 0; }
hdu1274
2 1(1a2b1(ab)1c) 3(ab2(4ab))
abbabc abaaaabaaaababaaaabaaaababaaaabaaaab
以下转载代码:
#include <iostream> #include <cctype> #include <cstring> #include <string> using namespace std; string s; int fun(int ith) { int k,e; char c; for(c=s[ith++];ith<s.size()&&c!=')';c=s[ith++])//递归结束的条件是字符串结束或遇到右括号 { for(k=0;isdigit(c);c=s[ith++]) k=k*10+c-'0'; if(!k) k=1; if(c=='('){ while(k--) e=fun(ith); ith=e;//重置ith的值,到下层递归结束的位置 } else { while(k--) putchar(c); } } if(c==')') return ith;//返回本次读到结尾的位置 } int main() { int i,j,k,T; cin>>T; while(T--) { s.clear(); cin>>s; fun(0);//进入递归 cout<<endl; } return 0; }