Monday, June 6, 2011

11616 - Roman Numerals


#include<iostream>
#include<cstdio>
#include<string>
#include<map>
#include<cstdlib>
using namespace std;

string inp,RomNum [4005] = { "0", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X"};
map < string,int >MP;
void genRom();

int main()
{
    int n;
    //freopen("in.txt","r",stdin);
   
    genRom();
    while ( cin>>inp )
    {
        n = atoi(inp.c_str());
        if ( n )
            cout<<RomNum[n]<<endl;
        else
            cout<<MP[inp]<<endl;
    }

    return 0;
}

void genRom()
{
    int i,tmp;

    for(i=0;i<=10;i++)
        MP[RomNum[i]] = i;

    for ( i = 11; i < 4000; i++ )
    {
        tmp = i;
        while ( tmp )
        {
            if ( tmp >= 900 && tmp < 4000 )
                if ( tmp / 100 == 9 )
                    RomNum [i] += "CM", tmp -= 900;
                else
                    RomNum [i] += "M", tmp -= 1000;

            if ( tmp >= 400 && tmp < 900 )
                if ( tmp / 100 == 4 )
                    RomNum [i] += "CD", tmp -= 400;
                else
                    RomNum [i] += "D", tmp -= 500;

            if ( tmp >= 90 && tmp < 400 )
                if ( tmp / 10 == 9 )
                    RomNum [i] += "XC", tmp -= 90;
                else
                    RomNum [i] += "C", tmp -= 100;

            if ( tmp >= 40 && tmp < 90 )
                if ( tmp / 10 == 4 )
                    RomNum [i] += "XL", tmp -= 40;
                else
                    RomNum [i] += "L", tmp -= 50;

            if ( tmp >= 1 && tmp < 40 )
                for ( int j = 10; j >= 1; j-- )
                    if ( tmp >= j )
                    {
                        RomNum [i] += RomNum [j];
                        tmp -= j;
                        break;
                    }
        }
        MP[RomNum[i]] = i;
    }
}

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.