MMASS - Mass of Molecule

Tác giả: khuc_tuan

Ngôn ngữ: Pascal

//{$A8,B-,C+,D+,E-,F-,G+,H+,I+,J-,K-,L+,M-,N+,O+,P+,Q+,R+,S+,T-,U-,V+,W-,X+,Y+,Z1}
// {$APPTYPE CONSOLE}
 {$mode delphi}

var
    a : array[0..110] of char;
    n : integer;

function get(l,r:integer):integer;
var
   i, c, sl: integer;
begin
    if l>r then begin get := 0; exit; end;
    if l=r then
    begin
        if a[l]='H' then get := 1;
        if a[l]='C' then get := 12;
        if a[l]='O' then get := 16;
        exit;
    end;
    if a[r] in ['C','H','O'] then
    begin
        get := get(l,r-1) + get(r,r);
        exit;
    end
    else if a[r] = ')' then
    begin
        c := 0;
        for i:=r downto l do
        begin
            if a[i]='(' then dec(c);
            if a[i]=')' then inc(c);
            if c=0 then
            begin
                get := get(i+1,r-1) + get(l,i-1);
                exit;
            end;
        end;
    end
    else
    begin
        sl := ord(a[r]) - ord('0');
        if a[r-1] in ['C','O','H'] then
        begin
            get := get(l,r-2) + get(r-1,r-1) * sl;
            exit;
        end;
        c := 0;
        for i:=r-1 downto l do
        begin
            if a[i]='(' then dec(c);
            if a[i]=')' then inc(c);
            if c=0 then
            begin
                get := sl * get(i+1,r-2) + get(l,i-1);
                exit;
            end;
        end;
    end;
end;

begin
    readln(a);
    n := Length(PChar(@a));
    writeln(get(0,n-1));
end.

Download