Monday, April 1, 2019

MMASS : Mass of Molecule

MMASS : Mass of Molecule
Link for the problem: MMASS

SOLUTION:

Mass of Molecule can be determined by knowing the mass of sub-molecules. A submolecule is always lie in between '(' and ')' in the formula and followed by an integer. The integer represents the number of times that submolecule exist in the molecule.
So, to find the mass of a submolecule we use a stack.
We will use following operations in for different characters of string  S : -

1.) If  S[i] is '(', Then push it in the stack. (left boundary of a submolecule)
2.) If it is 'C','O' or 'H' then push its corresponding mass in the stack.
3.) If it is an integer between 2 to 9, Then multiply this to top of stack.
4.) If S[i] is ')', i.e. right boundary of submolecule, then sum up to left boundary of molecule by popping out the stack.
5.) After getting mass of a submolecule, push it in the stack, As it can be part of another submolecule.

After doing all these operations, sum up the values of the stack to get the mass of molecule.

CODE:

#include <bits/stdc++.h>
using namespace std;
int main()
{
    string s;
    cin>>s;
    stack <int> st;
    int i,j,k,l;
    l=s.size();
    for(i=0;i<l;i++)
    {
        if(s[i]=='(')
        {
            st.push(s[i]);
        }
        else if(s[i]=='C')
        {
            st.push(12);
        }
        else if(s[i]=='O')
        st.push(16);
        else if(s[i]=='H')
        st.push(1);
        else if(s[i]>='1'&&s[i]<='9')
        {
            k=st.top();
            st.pop();
            st.push(k*(s[i]-'0'));
        }
        else if(s[i]==')')
        {
            int sm=0;
            while(st.top()!='(')
            {
                sm+=st.top();
                st.pop();
            }
            st.pop();
            st.push(sm);
        }
    }
    int sm=0;
    while(st.size())
    {
        sm+=st.top();
        st.pop();
    }
    cout<<sm<<endl;
    return 0;

}

No comments:

Post a Comment

CHEFST: Chef and the stones

CHEFST: Chef and the stones Link for the problem:  CHEFST SOLUTION: For a given max possible no of stones that can be removed from ea...