Problem Description
Problem Analysis
The English statement is awfully complicated.
It’s really just asking for the molar mass of a molecular formula.
Read each letter and map it to an atomic weight.
Watch out for cases like CO and H2O where the count is 1.
(Finally learned how to write subscripts in Markdown, by the way.)
I made things a bit harder for myself here
by using a recursive function to look up the atom count.
Hit a few snags while writing it,
but luckily it still went through in one AC.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
| #include<stdio.h>
#include<string.h>
int t,l;
char s[100];
int find(int m) {
if((s[m+1]>'A'&&s[m+1]<'Z')||(m+1==l)) {
if(t==0)
t=1;
return t;
} else {
t=t*10+s[m+1]-'0';
return find(++m);
}
}
int main() {
int n;
double sum;
scanf("%d",&n);
while(n--) {
scanf("%s",s);
l=strlen(s);
for(int i=sum=0; i<l; i++) {
if(s[i]=='C') {
t=0;
sum+=12.01*find(i);
} else if(s[i]=='H') {
t=0;
sum+=1.008*find(i);
} else if(s[i]=='O') {
t=0;
sum+=16.00*find(i);
} else if(s[i]=='N') {
t=0;
sum+=14.01*find(i);
} else
continue;
}
printf("%.3lf\n",sum);
}
return 0;
}
|
Problem link: 【UVa】[1586]Molar mass