Programming Contest Solutions

The following project page contains the solutions to some programming contest problems.

Poetry.cpp - On 25 Feb,2012.

#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <cmath>
using namespace std;

vector<string> split( const string& s, const string& delim =" " ) {
    vector<string> res;
    string t;
    for ( int i = 0 ; i != s.size() ; i++ ) {
        if ( delim.find( s[i] ) != string::npos ) {
            if ( !t.empty() ) {
                res.push_back( t );
                t = "";
            }
        } else {
            t += s[i];
        }
    }
    if ( !t.empty() ) {
        res.push_back(t);
    }
    return res;
}

vector<int> splitInt( const string& s, const string& delim =" " ) {
    vector<string> tok = split( s, delim );
    vector<int> res;
    for ( int i = 0 ; i != tok.size(); i++ )
        res.push_back( atoi( tok[i].c_str() ) );
    return res;
}

// BEGIN CUT HERE
#define ARRSIZE(x) (sizeof(x)/sizeof(x[0]))

template<typename T> void print( T a ) {
    cerr << a;
}
static void print( long long a ) {
    cerr << a << "L";
}
static void print( string a ) {
    cerr << '"' << a << '"';
}
template<typename T> void print( vector<T> a ) {
    cerr << "{";
    for ( int i = 0 ; i != a.size() ; i++ ) {
        if ( i != 0 ) cerr << ", ";
        print( a[i] );
    }
    cerr << "}" << endl;
}
template<typename T> void eq( int n, T have, T need ) {
    if ( have == need ) {
        cerr << "Case " << n << " passed." << endl;
    } else {
        cerr << "Case " << n << " failed: expected ";
        print( need );
        cerr << " received ";
        print( have );
        cerr << "." << endl;
    }
}
template<typename T> void eq( int n, vector<T> have, vector<T> need ) {
    if( have.size() != need.size() ) {
        cerr << "Case " << n << " failed: returned " << have.size() << " elements; expected " << need.size() << " elements.";
        print( have );
        print( need );
        return;
    }
    for( int i= 0; i < have.size(); i++ ) {
        if( have[i] != need[i] ) {
            cerr << "Case " << n << " failed. Expected and returned array differ in position " << i << ".";
            print( have );
            print( need );
            return;
        }
    }
    cerr << "Case " << n << " passed." << endl;
}
static void eq( int n, string have, string need ) {
    if ( have == need ) {
        cerr << "Case " << n << " passed." << endl;
    } else {
        cerr << "Case " << n << " failed: expected ";
        print( need );
        cerr << " received ";
        print( have );
        cerr << "." << endl;
    }
}
// END CUT HERE
class Poetry {
public:
    string rhymeScheme(vector <string> poem) {
        vector <string>::iterator string_it;
        string res, line, empty_line;
        string word;
        string::iterator ec;
        map<string,string> rhymes;
        res = "";
        string chars_in_poem = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        int current_char = 0;
        int blank_line = 1;

        for(string_it = poem.begin(); string_it != poem.end(); string_it++)
        {
            line = (*string_it);
            
            /* lower case it */

            transform(line.begin(),line.end(),line.begin(),::tolower);
        
            /* check blank line */

            empty_line = line;
            empty_line.erase(std::remove_if(empty_line.begin(), empty_line.end(), (int(*)(int))isspace), empty_line.end());
            if (empty_line.size() == 0)
            {
                res += " ";
                continue;
            }

            /* remove spaces (trailing) and first y */

            word = find_word(line);
            word.erase(std::remove_if(word.begin(), word.end(), (int(*)(int))isspace), word.end());
            if (word[0] == 'y')
                word = word.substr(1);

            /**
             * The idea is form the dictionary of the rhymes and fetch from the
             * dictionary if the rhyme already exist, if not add to the
             * dictionary for the new rhyme created according to the rule.
             */

            if (rhymes.count(word) > 0)
                res += rhymes[word];
            else
            {
                rhymes[word] += chars_in_poem[current_char];
                res += chars_in_poem[current_char];
                current_char++;
            }
        }
        return res;
    }

    string find_word(string line)
    {
        // find the last contiguous vowels
        string::iterator c;
        int v;
        int len = line.size();
        int found = 0;
        string sub_str;
        for(c= line.end()-1; c != line.begin(); --c)
        {
            v = *c;
            if ( (v == 'y' && (c != line.begin() || c != line.end()-1)) || v == 'a' || v == 'e' || v == 'i' || v == 'o' || v == 'u')
            {
                len -= 1;
                found = 1;
            }
            else
            {
                if (found == 0)
                {
                    len -= 1;
                }
                else 
                    break;
            }
        }

        sub_str = line.substr(len);
        return sub_str;
    }

};
// BEGIN CUT HERE
int main( int argc, char* argv[] ) {
    {
        string poemARRAY[] = {"problem",
            "anotherproblem",
            "this stupid haiku"};
        vector <string> poem( poemARRAY, poemARRAY+ARRSIZE(poemARRAY) );
        Poetry theObject;
        eq(0, theObject.rhymeScheme(poem),"aab");
    }
    {
        string poemARRAY[] = {"I hope this problem",
            "is a whole lot better than",
            "this stupid haiku"};
        vector <string> poem( poemARRAY, poemARRAY+ARRSIZE(poemARRAY) );
        Poetry theObject;
        eq(0, theObject.rhymeScheme(poem),"abc");
    }

    {
        string poemARRAY[] = {"     ",
            "Measure your height",
            "AND WEIGHT      ",
            "said the doctor",
            "",
            "And make sure to take your pills",
            "   to   cure   your    ills",
            "Every",
            "DAY"};
        vector <string> poem( poemARRAY, poemARRAY+ARRSIZE(poemARRAY) );
        Poetry theObject;
        eq(1, theObject.rhymeScheme(poem)," aab ccde");
    }
    {
        string poemARRAY[] = {"One bright day in the middle of the night",
            "Two dead boys got up to fight",
            "Back to back they faced each other",
            "Drew their swords and shot each other",
            "",
            "A deaf policeman heard the noise",
            "And came to arrest the two dead boys",
            "And if you dont believe this lie is true",
            "Ask the blind man he saw it too"};
        vector <string> poem( poemARRAY, poemARRAY+ARRSIZE(poemARRAY) );
        Poetry theObject;
        eq(2, theObject.rhymeScheme(poem),"aabb cdef");
    }
    {
        string poemARRAY[] = {"",
            "",
            "",
            ""};
        vector <string> poem( poemARRAY, poemARRAY+ARRSIZE(poemARRAY) );
        Poetry theObject;
        eq(3, theObject.rhymeScheme(poem),"    ");
    }
    {
        string poemARRAY[] = {"This poem has uppercase letters",
            "In its rhyme scheme",
            "Alpha", "Blaster", "Cat", "Desert", "Elephant", "Frog", "Gulch", 
            "Horse", "Ireland", "Jam", "Krispy Kreme", "Loofah", "Moo", "Narf",
            "Old", "Pink", "Quash", "Rainbow", "Star", "Tour", "Uvula", "Very",
            "Will", "Xmas", "Young", "Zed", "deception", "comic", "grout",
            "oval", "cable", "rob", "steal", "steel", "weak"};
        vector <string> poem( poemARRAY, poemARRAY+ARRSIZE(poemARRAY) );
        Poetry theObject;
        eq(4, theObject.rhymeScheme(poem),"abcdefghibjkblmnopqrstcuvwxyzABCbDEFG");
    }
    {
        string poemARRAY[] = {" ",
            "     ",
            "This poem",
            "         ",
            " ",
            " ",
            "",
            "Has lots of blank lines",
            " ",
            "      ",
            "                                            ",
            "         ",
            " ",
            "              ",
            "                                                  ",
            "  in      it           "};
        vector <string> poem( poemARRAY, poemARRAY+ARRSIZE(poemARRAY) );
        Poetry theObject;
        eq(5, theObject.rhymeScheme(poem),"  a    b       c");
    }
    {
        string poemARRAY[] = {"too bad   your",
            "     solution went   sour"};
        vector <string> poem( poemARRAY, poemARRAY+ARRSIZE(poemARRAY) );
        Poetry theObject;
        eq(6, theObject.rhymeScheme(poem),"aa");
    }

}

DengklekMakingChains.cpp - On 10 Feb,2012.

#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <cmath>
#include <regex.h>

using namespace std;

vector<string> split( const string& s, const string& delim =" " ) {
    vector<string> res;
    string t;
    for ( int i = 0 ; i != s.size() ; i++ ) {
        if ( delim.find( s[i] ) != string::npos ) {
            if ( !t.empty() ) {
                res.push_back( t );
                t = "";
            }
        } else {
            t += s[i];
        }
    }
    if ( !t.empty() ) {
        res.push_back(t);
    }
    return res;
}

vector<int> splitInt( const string& s, const string& delim =" " ) {
    vector<string> tok = split( s, delim );
    vector<int> res;
    for ( int i = 0 ; i != tok.size(); i++ )
        res.push_back( atoi( tok[i].c_str() ) );
    return res;
}

// BEGIN CUT HERE
#define ARRSIZE(x) (sizeof(x)/sizeof(x[0]))

template<typename T> void print( T a ) {
    cerr << a;
}
static void print( long long a ) {
    cerr << a << "L";
}
static void print( string a ) {
    cerr << '"' << a << '"';
}
template<typename T> void print( vector<T> a ) {
    cerr << "{";
    for ( int i = 0 ; i != a.size() ; i++ ) {
        if ( i != 0 ) cerr << ", ";
        print( a[i] );
    }
    cerr << "}" << endl;
}
template<typename T> void eq( int n, T have, T need ) {
    if ( have == need ) {
        cerr << "Case " << n << " passed." << endl;
    } else {
        cerr << "Case " << n << " failed: expected ";
        print( need );
        cerr << " received ";
        print( have );
        cerr << "." << endl;
    }
}
template<typename T> void eq( int n, vector<T> have, vector<T> need ) {
    if( have.size() != need.size() ) {
        cerr << "Case " << n << " failed: returned " << have.size() << " elements; expected " << need.size() << " elements.";
        print( have );
        print( need );
        return;
    }
    for( int i= 0; i < have.size(); i++ ) {
        if( have[i] != need[i] ) {
            cerr << "Case " << n << " failed. Expected and returned array differ in position " << i << ".";
            print( have );
            print( need );
            return;
        }
    }
    cerr << "Case " << n << " passed." << endl;
}
static void eq( int n, string have, string need ) {
    if ( have == need ) {
        cerr << "Case " << n << " passed." << endl;
    } else {
        cerr << "Case " << n << " failed: expected ";
        print( need );
        cerr << " received ";
        print( have );
        cerr << "." << endl;
    }
}
// END CUT HERE
class DengklekMakingChains {
public:
    string getstring(vector<string> v)
    {
        string s;
        for(int i=0; i<v.size();i++)
        {
            s += v[i];
        }
        return s;
    }

    int maxlen(string s)
    {
        int sum_so_far = 0;
        int maxsum = 0;
        int i=0,num;
        string c;
        string dot(".");
        for(i=0;i<=s.size()-1;i++)
        {
            c = s[i];
            if (c.compare(dot) == 0)
            {
                if (sum_so_far > maxsum)
                    maxsum = sum_so_far;
                sum_so_far = 0;
            }
            else
            {
                c = s[i];
                num = atoi(c.c_str());
                sum_so_far += num;
            }

        }
        return maxsum;
    }

    int maxBeauty(vector <string> chains) {
        int res=0;
        int maxlenout;
        string result;
        sort(chains.begin(),chains.end());

        result = getstring(chains);
        maxlenout = maxlen(result);
        res = maxlenout;
        int left_max=0;
        int middle_total=0;
        int right_max=0;
        string first,last;

        string dot(".");
        string c;

        int num;
        print(chains);

        for (int i=0; i<=chains.size()-1;i++)
        {
            c = chains[i];
            first = c[0];
            last = c[c.size()-1];
            if (first.compare(dot) == 0 && last.compare(dot) != 0)
            {
                num = maxlen(c);
                if (num > left_max)
                    left_max = num;
            }
            if (first.compare(dot) != 0 && last.compare(dot) == 0)
            {
                num = maxlen(c);
                if (num > right_max)
                    right_max = num;
            }
            if (first.compare(dot) != 0 && last.compare(dot) != 0)
            {
                num = maxlen(c);
                middle_total += num;
            }


        }
        res = left_max + right_max + middle_total;

        /**
        while(next_permutation(chains.begin(), chains.end()))
        {
            result = getstring(chains);
            maxlenout = maxlen(result);

            if (maxlenout > res)
                res = maxlenout;
        }
        **/

        return res;
    }

};
// BEGIN CUT HERE
int main( int argc, char* argv[] ) {
    {
        string chainsARRAY[] = {".15", "7..", "402", "..3"};
        vector <string> chains( chainsARRAY, chainsARRAY+ARRSIZE(chainsARRAY) );
        DengklekMakingChains theObject;
        eq(0, theObject.maxBeauty(chains),19);
    }
    {
        string chainsARRAY[] = {"..1", "7..", "567", "24.", "8..", "234"};
        vector <string> chains( chainsARRAY, chainsARRAY+ARRSIZE(chainsARRAY) );
        DengklekMakingChains theObject;
        eq(1, theObject.maxBeauty(chains),36);
    }
    {
        string chainsARRAY[] = {"...", "..."};
        vector <string> chains( chainsARRAY, chainsARRAY+ARRSIZE(chainsARRAY) );
        DengklekMakingChains theObject;
        eq(2, theObject.maxBeauty(chains),0);
    }
    {
        string chainsARRAY[] = {"16.", "9.8", ".24", "52.", "3.1", "532", "4.4", "111"};
        vector <string> chains( chainsARRAY, chainsARRAY+ARRSIZE(chainsARRAY) );
        DengklekMakingChains theObject;
        eq(3, theObject.maxBeauty(chains),28);
    }
    {
        string chainsARRAY[] = {"..1", "3..", "2..", ".7."};
        vector <string> chains( chainsARRAY, chainsARRAY+ARRSIZE(chainsARRAY) );
        DengklekMakingChains theObject;
        eq(4, theObject.maxBeauty(chains),7);
    }
    {
        string chainsARRAY[] = {"412", "..7", ".58", "7.8", "32.", "6..", "351", "3.9", "985", "...", ".46"};
        vector <string> chains( chainsARRAY, chainsARRAY+ARRSIZE(chainsARRAY) );
        DengklekMakingChains theObject;
        eq(5, theObject.maxBeauty(chains),58);
    }
}
// END CUT HERE

DengklekTryingToSleep.cpp - On 10 Feb,2012.

#include <algorithm>
#include <string>
#include <vector>
using namespace std;

class DengklekTryingToSleep {
public:
    int minDucks(vector <int> ducks) {
        int res=0;
        sort(ducks.begin(), ducks.end());
        int min, max;
        min = ducks[0];
        max = ducks[ducks.size()-1];
        for(int i=min; i<=max;i++)
        {
            if (binary_search(ducks.begin(),ducks.end(),i))
                continue;
            else
                res++;
        }

        return res;
    }

};

BettingMoney.cpp - On 05 Feb,2012.

/* Topcoder Problem Statement:
 * http://www.topcoder.com/stat?c=problem_statement&pm=2297&rd=4775
 *
 * Definition:
 *
 * Class:   BettingMoney
 * Method:  moneyMade
 * Parameters:  vector<int>, vector<int>, int
 * Returns: int
 * Method signature:    int moneyMade(vector<int> amounts,vector<int> centsPerDollar, int finalResult)
 */

#include<iostream>
#include<vector>

using namespace std;

class BettingMoney {
    public:
        int moneyMade(vector<int> amounts, vector<int> centsPerDollar, int finalResult)
        {
            int netgain=0;
            int resAmount, resCentsPerDollar;
            resAmount = amounts[finalResult];
            resCentsPerDollar = centsPerDollar[finalResult];
            for (int i=0; i < amounts.size() ; i++)
            {
                if (i == finalResult)
                    continue;
                netgain += amounts[i];
            }

            netgain = (netgain*100) - (resAmount * resCentsPerDollar);
            return netgain;
        }
};

int main(int argc, char *argv[])
{
    BettingMoney obj;
    vector<int> v1, v2;
    v1.push_back(10);
    v1.push_back(20);
    v1.push_back(30);

    v2.push_back(20);
    v2.push_back(30);
    v2.push_back(40);

    int finalResult=1;
    cout<<obj.moneyMade(v1,v2,finalResult);

}

userName.cpp - On 05 Feb,2012.

/***
  TopCoder Problem Statment:
  http://www.topcoder.com/stat?c=problem_statement&pm=2913&rd=5849

  The interface definition of the problem statement is given in Java, it is
  different for C++ and correct one is available from the arena.

**/

#include <vector>
#include <string>
#include <iostream>
#include <sstream>
#include <algorithm>

using namespace std;

class UserName {
    public:
        string newMember(vector<string> existingNames,string newName) {
            // code implementing the logic
            vector<string>::iterator it = find(existingNames.begin(), existingNames.end(), newName);

            if (it!= existingNames.end())
                for(int i = 1; i < (50 - newName.length()); i++) {
                    ostringstream oss;
                    oss <<newName<<i;
                    string check(oss.str());
                    vector<string>::iterator it2 = find(existingNames.begin(), existingNames.end(), check);
                    if (it2 == existingNames.end())
                        return check;
                }
            else
                return newName;
        }
};

int main()
{
    UserName uname;
    vector<string> existingNames;
    string newName1,newName2,newName3;

    existingNames.push_back("senthil");
    existingNames.push_back("Kumaran");
    existingNames.push_back("Senthil2");
    existingNames.push_back("Senthil1");
    existingNames.push_back("Kumaran4");

    newName1 = "Senthil";
    newName2 = "Kumaran";
    newName3 = "OR";
    cout << uname.newMember(existingNames, newName1) <<"\n";
    cout << uname.newMember(existingNames, newName2) <<"\n";
    cout << uname.newMember(existingNames, newName3) <<"\n";

    return 0;
}

MatchMaking.cpp - On 05 Feb,2012.

/** TopCoder Problem Statement:
 *
 * http://www.topcoder.com/stat?c=problem_statement&pm=2911&rd=5849&rm=&cr=7446789

   Definition

   Class: MatchMaking
   Method: makeMatch
   Parameters: vector <string>, vector <string>, vector <string>, vector <string>, string
   Returns: string
   Method signature:
   string makeMatch(vector <string> namesWomen, vector <string> answersWomen,
   vector <string> namesMen, vector <string> answersMen, string queryWoman)
  (be sure your method is public)
 *
 */

#include<iostream>
#include<vector>
#include<string>
#include<map>

using namespace std;

class MatchMaking {
    public:
        string makeMatch(vector <string> namesWomen, vector <string> answersWomen, 
                vector <string> namesMen, vector <string> answersMen,
                string queryWoman)
        {
            map<string,string> women;
            map<string,string> men;
            map<string,string>:: iterator wi,mi;
            map<string,string> suitablematch;

            string womanname,manname;
            string womanans, manans;
            int matchrank=0;
            int points=0;

            for (int i=0; i < namesWomen.size(); i++)
            {
                /* is this unique to map datastructure */
                women[namesWomen[i]] = answersWomen[i];
                men[namesMen[i]] = answersMen[i];
            }

            /* Algorithm/ Strategy
             * For each woman from the map, take her answer
             * and iterate through the answers of mens do a bitwise
             * AND and get the result. For the maximum value, let
             * her escape with him.
             *
             */
            for(wi = women.begin(); wi !=women.end(); wi++)
            {
                womanname = wi->first;
                womanans = wi->second;
                matchrank = 0;
                for (mi = men.begin(); mi != men.end(); mi++)
                {
                    manans = mi->second;
                    points = find_match(womanans, manans);
                    if (points > matchrank)
                    {
                        matchrank = points;
                        suitablematch[womanname] = mi->first;
                    }

                }
                //womens.erase(womansname);
                men.erase(suitablematch[womanname]);

            }

            return suitablematch[queryWoman];
        }

        int find_match(string str1,string str2)
        {
            int n,score=0;
            n = str1.size();
            for(int i=0; i< n; i++)
            {
                if (str1[i] == str2[i])
                    score++;
            }
            return score;
        }

};

int main(int argc, char *argv[])
{
    MatchMaking obj;
    vector <string> nW,aW,nM,aM;
    string match;
    nW.push_back("Constance");
    nW.push_back("Bertha");
    nW.push_back("Alice");
    
    aW.push_back("aaba");
    aW.push_back("baab");
    aW.push_back("aaaa");

    nM.push_back("Chip");
    nM.push_back("Biff");
    nM.push_back("Abe");

    aM.push_back("bbaa");
    aM.push_back("baaa");
    aM.push_back("aaab");

    match = obj.makeMatch(nW,aW,nM,aM,"Bertha");
    cout<<match<<endl;
}

NoRepeatPlaylist.cpp - On 31 Jan,2012.

#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <cmath>
using namespace std;

vector<string> split( const string& s, const string& delim =" " ) {
    vector<string> res;
    string t;
    for ( int i = 0 ; i != s.size() ; i++ ) {
        if ( delim.find( s[i] ) != string::npos ) {
            if ( !t.empty() ) {
                res.push_back( t );
                t = "";
            }
        } else {
            t += s[i];
        }
    }
    if ( !t.empty() ) {
        res.push_back(t);
    }
    return res;
}

vector<int> splitInt( const string& s, const string& delim =" " ) {
    vector<string> tok = split( s, delim );
    vector<int> res;
    for ( int i = 0 ; i != tok.size(); i++ )
        res.push_back( atoi( tok[i].c_str() ) );
    return res;
}

// BEGIN CUT HERE
#define ARRSIZE(x) (sizeof(x)/sizeof(x[0]))

template<typename T> void print( T a ) {
    cerr << a;
}
static void print( long long a ) {
    cerr << a << "L";
}
static void print( string a ) {
    cerr << '"' << a << '"';
}
template<typename T> void print( vector<T> a ) {
    cerr << "{";
    for ( int i = 0 ; i != a.size() ; i++ ) {
        if ( i != 0 ) cerr << ", ";
        print( a[i] );
    }
    cerr << "}" << endl;
}
template<typename T> void eq( int n, T have, T need ) {
    if ( have == need ) {
        cerr << "Case " << n << " passed." << endl;
    } else {
        cerr << "Case " << n << " failed: expected ";
        print( need );
        cerr << " received ";
        print( have );
        cerr << "." << endl;
    }
}
template<typename T> void eq( int n, vector<T> have, vector<T> need ) {
    if( have.size() != need.size() ) {
        cerr << "Case " << n << " failed: returned " << have.size() << " elements; expected " << need.size() << " elements.";
        print( have );
        print( need );
        return;
    }
    for( int i= 0; i < have.size(); i++ ) {
        if( have[i] != need[i] ) {
            cerr << "Case " << n << " failed. Expected and returned array differ in position " << i << ".";
            print( have );
            print( need );
            return;
        }
    }
    cerr << "Case " << n << " passed." << endl;
}
static void eq( int n, string have, string need ) {
    if ( have == need ) {
        cerr << "Case " << n << " passed." << endl;
    } else {
        cerr << "Case " << n << " failed: expected ";
        print( need );
        cerr << " received ";
        print( have );
        cerr << "." << endl;
    }
}
// END CUT HERE
class NoRepeatPlaylist {
public:
    int numPlaylists(int N, int M, int P) {
        int res;
        if (P < N)
            return 0;
        return res;
    }

};

int main( int argc, char* argv[] ) {
    {
        NoRepeatPlaylist theObject;
        eq(0, theObject.numPlaylists(1, 0, 3),1);
    }
    {
        NoRepeatPlaylist theObject;
        eq(1, theObject.numPlaylists(1, 1, 3),0);
    }
    {
        NoRepeatPlaylist theObject;
        eq(2, theObject.numPlaylists(2, 0, 3),6);
    }
    {
        NoRepeatPlaylist theObject;
        eq(3, theObject.numPlaylists(4, 0, 4),24);
    }
    {
        NoRepeatPlaylist theObject;
        eq(4, theObject.numPlaylists(2, 1, 4),2);
    }
    {
        NoRepeatPlaylist theObject;
        eq(5, theObject.numPlaylists(50, 5, 100),222288991);
    }
}

UnsortedSequence.cpp - On 31 Jan,2012.

#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;

class UnsortedSequence {
public:
    vector <int> getUnsorted(vector <int> s) {
        vector <int> res;
        vector <int> empty;
        vector <int>::iterator it;
        stable_sort(s.begin(),s.end());
        res = s;
        int last_element;
        int total_len;
        total_len = res.size()-1;
        last_element = res[res.size()-1];
        res.erase(res.begin()+res.size()-1);
        // insert it at the correct place
        if (res.size() == 0)
            return empty;


        int counter;
        counter = total_len;
        for (it=res.end(); it>=res.begin(); it--)
            if (*it < last_element)
                break;
            else
                counter--;

        if (counter < 0)
            return empty;
        
        res.insert(res.begin()+counter,last_element);
        
        return res;
    }

};

GogoXCake.cpp - On 20 Jan,2012.

// BEGIN CUT HERE

// END CUT HERE

#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <cmath>
using namespace std;

vector<string> split( const string& s, const string& delim =" " ) {
    vector<string> res;
    string t;
    for ( int i = 0 ; i != s.size() ; i++ ) {
        if ( delim.find( s[i] ) != string::npos ) {
            if ( !t.empty() ) {
                res.push_back( t );
                t = "";
            }
        } else {
            t += s[i];
        }
    }
    if ( !t.empty() ) {
        res.push_back(t);
    }
    return res;
}

vector<int> splitInt( const string& s, const string& delim =" " ) {
    vector<string> tok = split( s, delim );
    vector<int> res;
    for ( int i = 0 ; i != tok.size(); i++ )
        res.push_back( atoi( tok[i].c_str() ) );
    return res;
}


// BEGIN CUT HERE
#define ARRSIZE(x) (sizeof(x)/sizeof(x[0]))

template<typename T> void print( T a ) {
    cerr << a;
}
static void print( long long a ) {
    cerr << a << "L";
}
static void print( string a ) {
    cerr << '"' << a << '"';
}
template<typename T> void print( vector<T> a ) {
    cerr << "{";
    for ( int i = 0 ; i != a.size() ; i++ ) {
        if ( i != 0 ) cerr << ", ";
        print( a[i] );
    }
    cerr << "}" << endl;
}
template<typename T> void eq( int n, T have, T need ) {
    if ( have == need ) {
        cerr << "Case " << n << " passed." << endl;
    } else {
        cerr << "Case " << n << " failed: expected ";
        print( need );
        cerr << " received ";
        print( have );
        cerr << "." << endl;
    }
}
template<typename T> void eq( int n, vector<T> have, vector<T> need ) {
    if( have.size() != need.size() ) {
        cerr << "Case " << n << " failed: returned " << have.size() << " elements; expected " << need.size() << " elements.";
        print( have );
        print( need );
        return;
    }
    for( int i= 0; i < have.size(); i++ ) {
        if( have[i] != need[i] ) {
            cerr << "Case " << n << " failed. Expected and returned array differ in position " << i << ".";
            print( have );
            print( need );
            return;
        }
    }
    cerr << "Case " << n << " passed." << endl;
}
static void eq( int n, string have, string need ) {
    if ( have == need ) {
        cerr << "Case " << n << " passed." << endl;
    } else {
        cerr << "Case " << n << " failed: expected ";
        print( need );
        cerr << " received ";
        print( have );
        cerr << "." << endl;
    }
}
// END CUT HERE
class GogoXCake {
public:
    string solve(vector <string> cake, vector <string> cutter) {
        string res="YES";
        vector<string> initial;
        string item="X";
        int row = (int)cake[0].size();
        int col = (int)cake.size();
        for (int i=0; i < col; i++)
        {
            string rowentry="";
            for(int j=0; j < row; j++)
                rowentry += item;
            initial.push_back(rowentry);
        }
        print(initial);
        print(cake);
        print(cutter);
        return res;
    }

};
// BEGIN CUT HERE
int main( int argc, char* argv[] ) {
    {
        string cakeARRAY[] = {"X.X"
           ,"..."
           ,"..."
           ,"X.X"};
        vector <string> cake( cakeARRAY, cakeARRAY+ARRSIZE(cakeARRAY) );
        string cutterARRAY[] = {".X"
           ,".."
           ,"X."};
        vector <string> cutter( cutterARRAY, cutterARRAY+ARRSIZE(cutterARRAY) );
        GogoXCake theObject;
        eq(0, theObject.solve(cake, cutter),"YES");
    }
    {
        string cakeARRAY[] = {"..XX"
           ,"...X"
           ,"X..."
           ,"XX.."};
        vector <string> cake( cakeARRAY, cakeARRAY+ARRSIZE(cakeARRAY) );
        string cutterARRAY[] = {".."
           ,".."};
        vector <string> cutter( cutterARRAY, cutterARRAY+ARRSIZE(cutterARRAY) );
        GogoXCake theObject;
        eq(1, theObject.solve(cake, cutter),"NO");
    }
    {
        string cakeARRAY[] = {"...X..."};
        vector <string> cake( cakeARRAY, cakeARRAY+ARRSIZE(cakeARRAY) );
        string cutterARRAY[] = {"..."};
        vector <string> cutter( cutterARRAY, cutterARRAY+ARRSIZE(cutterARRAY) );
        GogoXCake theObject;
        eq(2, theObject.solve(cake, cutter),"YES");
    }
    {
        string cakeARRAY[] = {".X."
           ,"X.X"
           ,".X."};
        vector <string> cake( cakeARRAY, cakeARRAY+ARRSIZE(cakeARRAY) );
        string cutterARRAY[] = {"."};
        vector <string> cutter( cutterARRAY, cutterARRAY+ARRSIZE(cutterARRAY) );
        GogoXCake theObject;
        eq(3, theObject.solve(cake, cutter),"YES");
    }
    {
        string cakeARRAY[] = {"XXXXXXX"
           ,"X.....X"
           ,"X.....X"
           ,"X.....X"
           ,"XXXXXXX"};
        vector <string> cake( cakeARRAY, cakeARRAY+ARRSIZE(cakeARRAY) );
        string cutterARRAY[] = {".X."
           ,"XXX"
           ,".X."};
        vector <string> cutter( cutterARRAY, cutterARRAY+ARRSIZE(cutterARRAY) );
        GogoXCake theObject;
        eq(4, theObject.solve(cake, cutter),"NO");
    }
    {
        string cakeARRAY[] = {".."
           ,"X."
           ,".X"};
        vector <string> cake( cakeARRAY, cakeARRAY+ARRSIZE(cakeARRAY) );
        string cutterARRAY[] = {".."
           ,".X"
           ,"X."};
        vector <string> cutter( cutterARRAY, cutterARRAY+ARRSIZE(cutterARRAY) );
        GogoXCake theObject;
        eq(5, theObject.solve(cake, cutter),"NO");
    }
    {
        string cakeARRAY[] = {"X.."
           ,".XX"
           ,".XX"};
        vector <string> cake( cakeARRAY, cakeARRAY+ARRSIZE(cakeARRAY) );
        string cutterARRAY[] = {".XX"
           ,".XX"
           ,"X.."};
        vector <string> cutter( cutterARRAY, cutterARRAY+ARRSIZE(cutterARRAY) );
        GogoXCake theObject;
        eq(6, theObject.solve(cake, cutter),"NO");
    }
}
// END CUT HERE

GogoXBallsAndBinsEasy.cpp - On 20 Jan,2012.

#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <cstdio>
#include <cstdlib>
using namespace std;

class GogoXBallsAndBinsEasy {
public:
    int solve(vector <int> T) {
        int res=0;
        int count, totalcount;
        int elem;
        vector <int> PT = T;
        do {
            count = 0;
            totalcount = 0;
            for(elem = 0; elem <= (int)PT.size()-1; elem++)
            {
                if (PT[elem] > T[elem])
                {
                    count = PT[elem] - T[elem];
                    totalcount += count;
                }
            }
            if (totalcount > res)
                res = totalcount;
        }
        while(next_permutation(PT.begin(), PT.end()));
        
        return res;
    }

};

LoveCalculator.cpp - On 04 Jan,2012.

#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <cstdio>
#include <cstdlib>
using namespace std;

class LoveCalculator {
public:
    string findBoy(string girl, vector <string> boys) {
        string boyname;
        int L,O,V,E;
        int gL,gO,gV,gE;
        string res;

        sort(boys.begin(), boys.end());

        int probability=0, max= -1;

        gL = count(girl.begin(),girl.end(), 'L');
        gO = count(girl.begin(),girl.end(), 'O');
        gV = count(girl.begin(),girl.end(), 'V');
        gE = count(girl.begin(),girl.end(), 'E');

        for(int i=0; i< boys.size(); i++)
        {
            L = gL; O = gO; V = gV; E = gE;
            boyname = boys[i];
            L += count(boyname.begin(), boyname.end(), 'L');
            O += count(boyname.begin(), boyname.end(), 'O');
            V += count(boyname.begin(), boyname.end(), 'V');
            E += count(boyname.begin(), boyname.end(), 'E');
            probability = ((L+O)*(L+V)*(L+E)*(O+V)*(O+E)*(V+E))%100;

            if (probability > max)
            {
                max = probability;
                res = boyname;
            }
        }
        return res;
    }

};

MagicCandy.cpp - On 24 Dec,2011.

// BEGIN CUT HERE

// END CUT HERE

#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <cmath>
using namespace std;

vector<string> split( const string& s, const string& delim =" " ) {
    vector<string> res;
    string t;
    for ( int i = 0 ; i != s.size() ; i++ ) {
        if ( delim.find( s[i] ) != string::npos ) {
            if ( !t.empty() ) {
                res.push_back( t );
                t = "";
            }
        } else {
            t += s[i];
        }
    }
    if ( !t.empty() ) {
        res.push_back(t);
    }
    return res;
}

vector<int> splitInt( const string& s, const string& delim =" " ) {
    vector<string> tok = split( s, delim );
    vector<int> res;
    for ( int i = 0 ; i != tok.size(); i++ )
        res.push_back( atoi( tok[i].c_str() ) );
    return res;
}

// BEGIN CUT HERE
#define ARRSIZE(x) (sizeof(x)/sizeof(x[0]))

template<typename T> void print( T a ) {
    cerr << a;
}
static void print( long long a ) {
    cerr << a << "L";
}
static void print( string a ) {
    cerr << '"' << a << '"';
}
template<typename T> void print( vector<T> a ) {
    cerr << "{";
    for ( int i = 0 ; i != a.size() ; i++ ) {
        if ( i != 0 ) cerr << ", ";
        print( a[i] );
    }
    cerr << "}" << endl;
}
template<typename T> void eq( int n, T have, T need ) {
    if ( have == need ) {
        cerr << "Case " << n << " passed." << endl;
    } else {
        cerr << "Case " << n << " failed: expected ";
        print( need );
        cerr << " received ";
        print( have );
        cerr << "." << endl;
    }
}
template<typename T> void eq( int n, vector<T> have, vector<T> need ) {
    if( have.size() != need.size() ) {
        cerr << "Case " << n << " failed: returned " << have.size() << " elements; expected " << need.size() << " elements.";
        print( have );
        print( need );
        return;
    }
    for( int i= 0; i < have.size(); i++ ) {
        if( have[i] != need[i] ) {
            cerr << "Case " << n << " failed. Expected and returned array differ in position " << i << ".";
            print( have );
            print( need );
            return;
        }
    }
    cerr << "Case " << n << " passed." << endl;
}
static void eq( int n, string have, string need ) {
    if ( have == need ) {
        cerr << "Case " << n << " passed." << endl;
    } else {
        cerr << "Case " << n << " failed: expected ";
        print( need );
        cerr << " received ";
        print( have );
        cerr << "." << endl;
    }
}
// END CUT HERE
class MagicCandy {
public:

    int perfectsqr(int n)
    {
        int m;
        m = sqrt(n);
        if (n == m * m)
            return 1;
        else
            return 0;
    }

    vector<int> resultvector(vector<int> v)
    {
        int i=1;
        vector<int> e=v;
        for (i=v.size(); i >=1;i--)
        {
            if (perfectsqr(i))
                e.erase(e.begin()+i-1);
        }
        return e;

    }
    int whichOne(int n) {
        int res;
        int i;
        vector<int> v;
        for(i=1;i<=n;i++)
            v.push_back(i);

        while (v.size() != 1)
            v = resultvector(v);

        res = v[0];
        return res;
    }

};
// BEGIN CUT HERE
int main( int argc, char* argv[] ) {
    {
        MagicCandy theObject;
        eq(0, theObject.whichOne(5),5);
    }
    {
        MagicCandy theObject;
        eq(1, theObject.whichOne(9),7);
    }
    {
        MagicCandy theObject;
        eq(2, theObject.whichOne(20),17);
    }
    {
        MagicCandy theObject;
        eq(3, theObject.whichOne(5265),5257);
    }
    {
        MagicCandy theObject;
        eq(4, theObject.whichOne(20111223),20110741);
    }
    {
        MagicCandy theObject;
        eq(5, theObject.whichOne(1),1);
    }
}
// END CUT HERE

MagicStonesStore.cpp - On 24 Dec,2011.

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

class MagicStonesStore {
public:

    int isprime(int n)
    {
        if (n <=1)
            return 0;
        if (n == 2)
            return 1;
        if (n%2 == 0)
            return 0;
        int m = sqrt(n);

        for (int i=3; i<=m; i+=2)
            if (n%i == 0)
                return 0;
        return 1;
    }

    string ableToDivide(int n) {
        string res;
        if (isprime(n))
            return "YES";
        else
        {
            int m = 2*n;
            for (int i = 2; i <m; i++)
                if (isprime(i) && isprime(m-i))
                    return "YES";
        }
            return "NO";
    }

};

MagicStonesStore2.cpp - On 24 Dec,2011.

// BEGIN CUT HERE

// END CUT HERE

#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <cmath>
using namespace std;

vector<string> split( const string& s, const string& delim =" " ) {
    vector<string> res;
    string t;
    for ( int i = 0 ; i != s.size() ; i++ ) {
        if ( delim.find( s[i] ) != string::npos ) {
            if ( !t.empty() ) {
                res.push_back( t );
                t = "";
            }
        } else {
            t += s[i];
        }
    }
    if ( !t.empty() ) {
        res.push_back(t);
    }
    return res;
}

vector<int> splitInt( const string& s, const string& delim =" " ) {
    vector<string> tok = split( s, delim );
    vector<int> res;
    for ( int i = 0 ; i != tok.size(); i++ )
        res.push_back( atoi( tok[i].c_str() ) );
    return res;
}

// BEGIN CUT HERE
#define ARRSIZE(x) (sizeof(x)/sizeof(x[0]))

template<typename T> void print( T a ) {
    cerr << a;
}
static void print( long long a ) {
    cerr << a << "L";
}
static void print( string a ) {
    cerr << '"' << a << '"';
}
template<typename T> void print( vector<T> a ) {
    cerr << "{";
    for ( int i = 0 ; i != a.size() ; i++ ) {
        if ( i != 0 ) cerr << ", ";
        print( a[i] );
    }
    cerr << "}" << endl;
}
template<typename T> void eq( int n, T have, T need ) {
    if ( have == need ) {
        cerr << "Case " << n << " passed." << endl;
    } else {
        cerr << "Case " << n << " failed: expected ";
        print( need );
        cerr << " received ";
        print( have );
        cerr << "." << endl;
    }
}
template<typename T> void eq( int n, vector<T> have, vector<T> need ) {
    if( have.size() != need.size() ) {
        cerr << "Case " << n << " failed: returned " << have.size() << " elements; expected " << need.size() << " elements.";
        print( have );
        print( need );
        return;
    }
    for( int i= 0; i < have.size(); i++ ) {
        if( have[i] != need[i] ) {
            cerr << "Case " << n << " failed. Expected and returned array differ in position " << i << ".";
            print( have );
            print( need );
            return;
        }
    }
    cerr << "Case " << n << " passed." << endl;
}
static void eq( int n, string have, string need ) {
    if ( have == need ) {
        cerr << "Case " << n << " passed." << endl;
    } else {
        cerr << "Case " << n << " failed: expected ";
        print( need );
        cerr << " received ";
        print( have );
        cerr << "." << endl;
    }
}
// END CUT HERE
class MagicStonesStore {
public:

    int isprime(int n)
    {
        if (n <=1)
            return 0;
        if (n == 2)
            return 1;
        if (n%2 == 0)
            return 0;
        int m = sqrt(n);

        for (int i=3; i<=m; i+=2)
            if (n%i == 0)
                return 0;
        return 1;
    }

    string ableToDivide(int n) {
        string res;
        if (isprime(n))
            return "YES";
        else
        {
            int m = 2*n;
            for (int i = 2; i <m; i++)
                if (isprime(i) && isprime(m-i))
                    return "YES";
        }
            return "NO";
    }

};
// BEGIN CUT HERE
int main( int argc, char* argv[] ) {
    {
        MagicStonesStore theObject;
        eq(0, theObject.ableToDivide(1),"NO");
    }
    {
        MagicStonesStore theObject;
        eq(1, theObject.ableToDivide(2),"YES");
    }
    {
        MagicStonesStore theObject;
        eq(2, theObject.ableToDivide(3),"YES");
    }
    {
        MagicStonesStore theObject;
        eq(3, theObject.ableToDivide(5),"YES");
    }
    {
        MagicStonesStore theObject;
        eq(4, theObject.ableToDivide(8),"YES");
    }

}
// END CUT HERE

FunnyFence.cpp - On 24 Dec,2011.

#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <cmath>
using namespace std;

vector<string> split( const string& s, const string& delim =" " ) {
    vector<string> res;
    string t;
    for ( int i = 0 ; i != s.size() ; i++ ) {
        if ( delim.find( s[i] ) != string::npos ) {
            if ( !t.empty() ) {
                res.push_back( t );
                t = "";
            }
        } else {
            t += s[i];
        }
    }
    if ( !t.empty() ) {
        res.push_back(t);
    }
    return res;
}

vector<int> splitInt( const string& s, const string& delim =" " ) {
    vector<string> tok = split( s, delim );
    vector<int> res;
    for ( int i = 0 ; i != tok.size(); i++ )
        res.push_back( atoi( tok[i].c_str() ) );
    return res;
}

// BEGIN CUT HERE
#define ARRSIZE(x) (sizeof(x)/sizeof(x[0]))

template<typename T> void print( T a ) {
    cerr << a;
}
static void print( long long a ) {
    cerr << a << "L";
}
static void print( string a ) {
    cerr << '"' << a << '"';
}
template<typename T> void print( vector<T> a ) {
    cerr << "{";
    for ( int i = 0 ; i != a.size() ; i++ ) {
        if ( i != 0 ) cerr << ", ";
        print( a[i] );
    }
    cerr << "}" << endl;
}
template<typename T> void eq( int n, T have, T need ) {
    if ( have == need ) {
        cerr << "Case " << n << " passed." << endl;
    } else {
        cerr << "Case " << n << " failed: expected ";
        print( need );
        cerr << " received ";
        print( have );
        cerr << "." << endl;
    }
}
template<typename T> void eq( int n, vector<T> have, vector<T> need ) {
    if( have.size() != need.size() ) {
        cerr << "Case " << n << " failed: returned " << have.size() << " elements; expected " << need.size() << " elements.";
        print( have );
        print( need );
        return;
    }
    for( int i= 0; i < have.size(); i++ ) {
        if( have[i] != need[i] ) {
            cerr << "Case " << n << " failed. Expected and returned array differ in position " << i << ".";
            print( have );
            print( need );
            return;
        }
    }
    cerr << "Case " << n << " passed." << endl;
}
static void eq( int n, string have, string need ) {
    if ( have == need ) {
        cerr << "Case " << n << " passed." << endl;
    } else {
        cerr << "Case " << n << " failed: expected ";
        print( need );
        cerr << " received ";
        print( have );
        cerr << "." << endl;
    }
}
// END CUT HERE
class FunnyFence {
public:
    int getLength(string s) {
        int i;
        int count=0;
        int res=0;
        char next;
        if (s[0] == '|') next = '-';
        if (s[0] == '-') next = '|';
        cout<<next;
        for(i = 1; i < s.size();i++)
        {
            if (s[i] == next)
            {
                count++;
                if (count > res)
                {
                    res = count;
                }
                if (next == '-') next = '|';
                if (next == '|') next = '-';
                cout<<"next";
                cout<<next;
            }
            else
            {
                count = 0;

            }

        }
        return res;
    }

};
// BEGIN CUT HERE
int main( int argc, char* argv[] ) {
    {
        FunnyFence theObject;
        eq(0, theObject.getLength("|-|-|"),5);
    }
    {
        FunnyFence theObject;
        eq(1, theObject.getLength("-|-|-|-"),7);
    }
    {
        FunnyFence theObject;
        eq(2, theObject.getLength("||||||"),1);
    }
    {
        FunnyFence theObject;
        eq(3, theObject.getLength("|-||-|-"),4);
    }
    {
        FunnyFence theObject;
        eq(4, theObject.getLength("|-|---|-|---|-|"),5);
    }
    {
        FunnyFence theObject;
        eq(5, theObject.getLength("|||-||--|--|---|-||-|-|-|--||---||-||-||-|--||"),8);
    }
}
// END CUT HERE

PointErasingTwo.cpp - On 13 Nov,2011.

// BEGIN CUT HERE

// END CUT HERE

#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <cmath>
using namespace std;

vector<string> split( const string& s, const string& delim =" " ) {
    vector<string> res;
    string t;
    for ( int i = 0 ; i != s.size() ; i++ ) {
        if ( delim.find( s[i] ) != string::npos ) {
            if ( !t.empty() ) {
                res.push_back( t );
                t = "";
            }
        } else {
            t += s[i];
        }
    }
    if ( !t.empty() ) {
        res.push_back(t);
    }
    return res;
}

vector<int> splitInt( const string& s, const string& delim =" " ) {
    vector<string> tok = split( s, delim );
    vector<int> res;
    for ( int i = 0 ; i != tok.size(); i++ )
        res.push_back( atoi( tok[i].c_str() ) );
    return res;
}

// BEGIN CUT HERE
#define ARRSIZE(x) (sizeof(x)/sizeof(x[0]))

template<typename T> void print( T a ) {
    cerr << a;
}
static void print( long long a ) {
    cerr << a << "L";
}
static void print( string a ) {
    cerr << '"' << a << '"';
}
template<typename T> void print( vector<T> a ) {
    cerr << "{";
    for ( int i = 0 ; i != a.size() ; i++ ) {
        if ( i != 0 ) cerr << ", ";
        print( a[i] );
    }
    cerr << "}" << endl;
}
template<typename T> void eq( int n, T have, T need ) {
    if ( have == need ) {
        cerr << "Case " << n << " passed." << endl;
    } else {
        cerr << "Case " << n << " failed: expected ";
        print( need );
        cerr << " received ";
        print( have );
        cerr << "." << endl;
    }
}
template<typename T> void eq( int n, vector<T> have, vector<T> need ) {
    if( have.size() != need.size() ) {
        cerr << "Case " << n << " failed: returned " << have.size() << " elements; expected " << need.size() << " elements.";
        print( have );
        print( need );
        return;
    }
    for( int i= 0; i < have.size(); i++ ) {
        if( have[i] != need[i] ) {
            cerr << "Case " << n << " failed. Expected and returned array differ in position " << i << ".";
            print( have );
            print( need );
            return;
        }
    }
    cerr << "Case " << n << " passed." << endl;
}
static void eq( int n, string have, string need ) {
    if ( have == need ) {
        cerr << "Case " << n << " passed." << endl;
    } else {
        cerr << "Case " << n << " failed: expected ";
        print( need );
        cerr << " received ";
        print( have );
        cerr << "." << endl;
    }
}
// END CUT HERE
class PointErasingTwo {
public:
    int getMaximum(vector <int> y) {
        int res;
        return res;
    }

};
// BEGIN CUT HERE
void main( int argc, char* argv[] ) {
    {
        int yARRAY[] = { 1, 2, 1, 1, 0, 4, 3 };
        vector <int> y( yARRAY, yARRAY+ARRSIZE(yARRAY) );
        PointErasingTwo theObject;
        eq(0, theObject.getMaximum(y),2);
    }
    {
        int yARRAY[] = { 0, 1 };
        vector <int> y( yARRAY, yARRAY+ARRSIZE(yARRAY) );
        PointErasingTwo theObject;
        eq(1, theObject.getMaximum(y),0);
    }
    {
        int yARRAY[] = { 0, 1, 2, 3, 4 };
        vector <int> y( yARRAY, yARRAY+ARRSIZE(yARRAY) );
        PointErasingTwo theObject;
        eq(2, theObject.getMaximum(y),3);
    }
    {
        int yARRAY[] = { 10, 19, 10, 19 };
        vector <int> y( yARRAY, yARRAY+ARRSIZE(yARRAY) );
        PointErasingTwo theObject;
        eq(3, theObject.getMaximum(y),0);
    }
    {
        int yARRAY[] = { 0, 23, 49, 50, 32, 0, 18, 50, 0, 28, 50, 27, 49, 0 };
        vector <int> y( yARRAY, yARRAY+ARRSIZE(yARRAY) );
        PointErasingTwo theObject;
        eq(4, theObject.getMaximum(y),5);
    }
}
// END CUT HERE

RowAndManyCoins.cpp - On 26 Oct,2011.

// BEGIN CUT HERE

// END CUT HERE

#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <cmath>
using namespace std;

vector<string> split( const string& s, const string& delim =" " ) {
    vector<string> res;
    string t;
    for ( int i = 0 ; i != s.size() ; i++ ) {
        if ( delim.find( s[i] ) != string::npos ) {
            if ( !t.empty() ) {
                res.push_back( t );
                t = "";
            }
        } else {
            t += s[i];
        }
    }
    if ( !t.empty() ) {
        res.push_back(t);
    }
    return res;
}

vector<int> splitInt( const string& s, const string& delim =" " ) {
    vector<string> tok = split( s, delim );
    vector<int> res;
    for ( int i = 0 ; i != tok.size(); i++ )
        res.push_back( atoi( tok[i].c_str() ) );
    return res;
}

// BEGIN CUT HERE
#define ARRSIZE(x) (sizeof(x)/sizeof(x[0]))

template<typename T> void print( T a ) {
    cerr << a;
}
static void print( long long a ) {
    cerr << a << "L";
}
static void print( string a ) {
    cerr << '"' << a << '"';
}
template<typename T> void print( vector<T> a ) {
    cerr << "{";
    for ( int i = 0 ; i != a.size() ; i++ ) {
        if ( i != 0 ) cerr << ", ";
        print( a[i] );
    }
    cerr << "}" << endl;
}
template<typename T> void eq( int n, T have, T need ) {
    if ( have == need ) {
        cerr << "Case " << n << " passed." << endl;
    } else {
        cerr << "Case " << n << " failed: expected ";
        print( need );
        cerr << " received ";
        print( have );
        cerr << "." << endl;
    }
}
template<typename T> void eq( int n, vector<T> have, vector<T> need ) {
    if( have.size() != need.size() ) {
        cerr << "Case " << n << " failed: returned " << have.size() << " elements; expected " << need.size() << " elements.";
        print( have );
        print( need );
        return;
    }
    for( int i= 0; i < have.size(); i++ ) {
        if( have[i] != need[i] ) {
            cerr << "Case " << n << " failed. Expected and returned array differ in position " << i << ".";
            print( have );
            print( need );
            return;
        }
    }
    cerr << "Case " << n << " passed." << endl;
}
static void eq( int n, string have, string need ) {
    if ( have == need ) {
        cerr << "Case " << n << " passed." << endl;
    } else {
        cerr << "Case " << n << " failed: expected ";
        print( need );
        cerr << " received ";
        print( have );
        cerr << "." << endl;
    }
}
// END CUT HERE
class RowAndManyCoins {
public:
    string getWinner(string cells) {
        string res;
        return res;
    }

};
// BEGIN CUT HERE
void main( int argc, char* argv[] ) {
    {
        RowAndManyCoins theObject;
        eq(0, theObject.getWinner("ABBB"),"Alice");
    }
    {
        RowAndManyCoins theObject;
        eq(1, theObject.getWinner("BBBB"),"Bob");
    }
    {
        RowAndManyCoins theObject;
        eq(2, theObject.getWinner("BA"),"Alice");
    }
    {
        RowAndManyCoins theObject;
        eq(3, theObject.getWinner("BABBABBB"),"Bob");
    }
    {
        RowAndManyCoins theObject;
        eq(4, theObject.getWinner("ABABBBABAABBAA"),"Alice");
    }
    {
        RowAndManyCoins theObject;
        eq(5, theObject.getWinner("BBBAAABBAAABBB"),"Bob");
    }
}
// END CUT HERE

WhichDay.cpp - On 01 Oct,2011.

#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <cmath>
using namespace std;

class WhichDay {
public:
    string getDay(vector <string> notOnThisDay) {

        int i = 0;
        string alldays[] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday","Saturday"};
        int size = notOnThisDay.size();
        vector<string>::const_iterator it;
        string res;
        for(i = 0; i <= 6; i++) {
            res = alldays[i];
            it = find(notOnThisDay.begin(), notOnThisDay.end(),res);
            if (it == notOnThisDay.end())
                return res;
        }
    }

};

TwiceString.cpp - On 01 Oct,2011.

// BEGIN CUT HERE

// END CUT HERE

#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <cmath>
using namespace std;

vector<string> split( const string& s, const string& delim =" " ) {
    vector<string> res;
    string t;
    for ( int i = 0 ; i != s.size() ; i++ ) {
        if ( delim.find( s[i] ) != string::npos ) {
            if ( !t.empty() ) {
                res.push_back( t );
                t = "";
            }
        } else {
            t += s[i];
        }
    }
    if ( !t.empty() ) {
        res.push_back(t);
    }
    return res;
}

vector<int> splitInt( const string& s, const string& delim =" " ) {
    vector<string> tok = split( s, delim );
    vector<int> res;
    for ( int i = 0 ; i != tok.size(); i++ )
        res.push_back( atoi( tok[i].c_str() ) );
    return res;
}

// BEGIN CUT HERE
#define ARRSIZE(x) (sizeof(x)/sizeof(x[0]))

template<typename T> void print( T a ) {
    cerr << a;
}
static void print( long long a ) {
    cerr << a << "L";
}
static void print( string a ) {
    cerr << '"' << a << '"';
}
template<typename T> void print( vector<T> a ) {
    cerr << "{";
    for ( int i = 0 ; i != a.size() ; i++ ) {
        if ( i != 0 ) cerr << ", ";
        print( a[i] );
    }
    cerr << "}" << endl;
}
template<typename T> void eq( int n, T have, T need ) {
    if ( have == need ) {
        cerr << "Case " << n << " passed." << endl;
    } else {
        cerr << "Case " << n << " failed: expected ";
        print( need );
        cerr << " received ";
        print( have );
        cerr << "." << endl;
    }
}
template<typename T> void eq( int n, vector<T> have, vector<T> need ) {
    if( have.size() != need.size() ) {
        cerr << "Case " << n << " failed: returned " << have.size() << " elements; expected " << need.size() << " elements.";
        print( have );
        print( need );
        return;
    }
    for( int i= 0; i < have.size(); i++ ) {
        if( have[i] != need[i] ) {
            cerr << "Case " << n << " failed. Expected and returned array differ in position " << i << ".";
            print( have );
            print( need );
            return;
        }
    }
    cerr << "Case " << n << " passed." << endl;
}
static void eq( int n, string have, string need ) {
    if ( have == need ) {
        cerr << "Case " << n << " passed." << endl;
    } else {
        cerr << "Case " << n << " failed: expected ";
        print( need );
        cerr << " received ";
        print( have );
        cerr << "." << endl;
    }
}

int Count(const std::string & str, const std::string & obj ) {
    int n = 0;
    std::string ::size_type pos = 0;
            while( (pos = obj.find( str, pos )) 
                                     != std::string::npos ) {
                        n++;
                                pos += str.size();
                                    }
                return n;
}
//
// END CUT HERE
class TwiceString {
public:
    string getShortest(string s) {
        string res, check, temp;
        temp = s + s;
        res = temp;
        size_t found;
        int startpos = s.size();
        for (int i = 1; i <= s.size()-1; i++)
        {
            check = temp;
            check.erase(startpos,i);
            found = check.find(s,1);
            if (found != string::npos)
                res = check;
        }

        return res;
    }

};
// BEGIN CUT HERE
int main( int argc, char* argv[] ) {
    {
        TwiceString theObject;
        eq(0, theObject.getShortest("aba"),"ababa");
    }
    {
        TwiceString theObject;
        eq(1, theObject.getShortest("xxxxx"),"xxxxxx");
    }
    {
        TwiceString theObject;
        eq(2, theObject.getShortest("topcoder"),"topcodertopcoder");
    }
    {
        TwiceString theObject;
        eq(3, theObject.getShortest("abracadabra"),"abracadabracadabra");
    }
}
// END CUT HERE

ZigZag.cpp - On 01 Oct,2011.

/**
    
Class: ZigZag

**/

#include<iostream>
#include<vector>
using namespace std;

class ZigZag
{
    public:
    int longestZigZag(vector <int> sequence)
    {
        int len;
        int prevsign=0;
        int sign;
        vector<int> resultseq;
        
        for (int i=0; i < sequence.size(); i++)
        {
            if (i == 0) 
            {
                resultseq.push_back(sequence[i]);
                continue;
            }
            if (i == 1)
            {
                resultseq.push_back(sequence[i]);
                if ((sequence[i] - sequence[i-1]) > 0)
                    prevsign = 1;
                else
                    prevsign = -1;
                continue;
            }
            if (sequence[i] == sequence[i-1])
                continue;

            if ((sequence[i] - sequence[i-1]) > 0)
                sign = 1;

            else
                sign = -1;

            if (prevsign != sign)
            {
                resultseq.push_back(sequence[i]);
            }
            else
            {
                resultseq[resultseq.size()-1] = sequence[i];
            }
            prevsign = sign;

        }

        len = resultseq.size();
        return len;
    }
};

int main(int argc, char *argv[])
{
    ZigZag obj;
    vector<int> sequence;
    sequence.push_back(1);
    sequence.push_back(17);
    sequence.push_back(5);
    sequence.push_back(10);
    sequence.push_back(13);
    sequence.push_back(15);
    sequence.push_back(10);
    sequence.push_back(5);
    sequence.push_back(16);
    sequence.push_back(8);
    cout<<obj.longestZigZag(sequence)<<endl;
}

Yatzee.cpp - On 01 Oct,2011.

/* TopCoder Problem Statement:
 * http://www.topcoder.com/stat?c=problem_statement&pm=1692&rd=4535
 *

   Class: YahtzeeScore
   Method: maxPoints
   Parameters: vector <int>
   Returns: int
   Method signature: int maxPoints(vector <int> toss)
 *
 * Solution:
 * Use count and unique from algorithm
 *
 */

#include<iostream>
#include<vector>
#include<algorithm>
#include<set>

using namespace std;


class YahtzeeScore {
    public:
        int maxPoints(vector <int> toss)
        {
            set<int> elements(toss.begin(), toss.end());
            set<int>::iterator set_iter;
            int value,count_times;
            int max = 0;
            for (set_iter = elements.begin(); set_iter != elements.end(); ++set_iter)
            {
                value = *set_iter;
                count_times = (int)count(toss.begin(), toss.end(), value);
                if ((count_times * value) > max)
                    max = count_times * value;
            }

            return max;

        }
};

int main(int argc, char *argv[])
{
    YahtzeeScore obj;
    vector<int> v1;
    v1.push_back(10);
    v1.push_back(20);
    v1.push_back(10);
    v1.push_back(10);
    cout<<obj.maxPoints(v1);
}

Xosceles.cpp - On 01 Oct,2011.

/*
 * Problem Statement:
 * http://www.topcoder.com/stat?c=problem_statement&pm=10152&rd=13952&rm=&cr=22684375
 * */

#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<math.h>

using namespace std;

class Xosceles{

    public:
        vector <string> draw(int xCount)
        {
            vector <string> ans;
            string st;
            int n = sqrt(xCount);
            int lastval=0;
            int i,j;
            if (pow(n, 2) == xCount)
                lastval = 2*n -1;
            else if ((n * (n+1)) == xCount)
                    lastval = 2*n;
            else
                return ans;
            for (i=0;i<n;i++)
            {
                st.assign(lastval, 'X');
                j = i;
                while (j)
                {
                    st[j-1] = '.';
                    st[lastval - j] =  '.';
                    j--;
                }
                ans.push_back(st);
            }

            reverse(ans.begin(), ans.end());
            return ans;
        }
};

int main(int argc, char *argv[])
{
    Xosceles obj;
    vector<string> xosceles_tri;
    xosceles_tri = obj.draw(2550);  
    for (int i=0; i <xosceles_tri.size(); i++)
        cout<<xosceles_tri[i]<<endl;
}

WidgetRepairs.cpp - On 01 Oct,2011.

/**

Class: WidgetRepairs

**/
#include<vector>
#include<iostream>
using namespace std;

class WidgetRepairs {
    public:
        int days(vector <int> arrivals, int numPerDay)
        {
            int days=0,remainder=0,towork=0;
            vector<int>::iterator iter;
            for(iter=arrivals.begin(); iter!=arrivals.end();++iter)
            {
                towork = *iter + remainder;
                if (towork == 0) continue;
                remainder = towork - numPerDay;
                if (remainder < 0)
                    remainder = 0;
                days++;
            }
            while (remainder > 0)
            {
                days++;
                remainder = remainder - numPerDay;
            }
            return days;
        }
};

int main(int argc, char *argv[])
{
    vector <int> arrivals;
    int numPerday=8;
    arrivals.push_back(10);
    arrivals.push_back(0);
    arrivals.push_back(0);
    arrivals.push_back(4);
    arrivals.push_back(20);
    WidgetRepairs obj;
    cout<<obj.days(arrivals,numPerday)<<endl;
}

vaish_solution.cpp - On 01 Oct,2011.

#include<iostream>
#include<vector>
using namespace std;

class binarycode
{
    public:
        vector<string> decode(string msg);
};

vector<string> binarycode::decode(string msg)
{

    string dstr1 = "0";
    vector<string> decodedstr;
    vector<string>::iterator it;
    string dstr2 = "0";
    int i=0,j=0,k=0;
    int Length;
    bool flag1 = false, flag2 = false;
    int m = 0;
    dstr1[i] = '0';
    dstr2[i] = '1';

    Length = msg.size();

    while((Length > 1) && (++i < Length) )
    {
        if(i ==1)
            dstr1[i] = ((msg[i-1] - '0')-(dstr1[i-1] - '0')) + '0' ;
        else
            dstr1[i] = ((msg[i-1] - '0')-((dstr1[i-1] - '0')+(dstr1[i-2] -'0')))+'0';
        if(dstr1[i] > '1'|| dstr1[i] < '0')
        {
            flag1 = true;
            break;
        }
        if(i == (Length - 1))
        {
            if((msg[i]-'0') != ((dstr1[i]-'0') +(dstr1[i-1] - '0')))
            {
                flag1 = true;
            }
        }

    }
    

    i = 0;
    while((Length > 1) && (++i < Length))
    {
        if(i ==1)
            dstr2[i] = ((msg[i-1] - '0')-(dstr2[i-1] - '0')) + '0';
        else
            dstr2[i] = ((msg[i-1] - '0')-((dstr2[i-1] - '0')+(dstr2[i-2] -'0')))+'0';
        if(dstr2[i] > '1' || dstr2[i] < '0')
        {
            flag2 = true;
            break;
        }
        if(i == (Length - 1))
        {
            if((msg[i]-'0') != ((dstr2[i]-'0') +(dstr2[i-1] - '0')))
            {
                flag2 = true;
            }
        }


    }
    j = 0;

    if(Length == 1)
    {
        if(msg.find('0') == 0)
            flag2 = true;
        if(msg.find('1') == 0)
            flag1 = true;
        if((msg.find('2') == 0) || (msg.find('3') == 0))
        {
            flag1 = true;
            flag2 = true;
        }
    }
                
    if(flag1 == true)
    {
        decodedstr.push_back("None");
    }
    else
    {
        string temp;
        while(j<Length)
        {
            temp +=dstr1[j];
            j++;
        }
        decodedstr.push_back(temp);

    }
    j = 0;
    if(flag2 == true)
    {
        decodedstr.push_back("None");
    }
    else
    {
        string temp;
        while(j<Length)
        {
            temp+=dstr2[j];
            j++;
        }
        decodedstr.push_back(temp);
    }
    return decodedstr;
}

int main()
{
    string s;
    vector<string> vstr;
    binarycode bc;
    cout<<"Enter the string to be decrypted"<<endl;
    cin>>s;
    vstr = bc.decode(s);
    cout<<vstr[0]<<","<<vstr[1]<<endl;
}
    

Underprimes.cpp - On 01 Oct,2011.

/**

Class: Underprimes

**/

#include<vector>
#include<cmath>
#include<iostream>

using namespace std;

class Underprimes {

    private:

        int isprime(int n)
        {
            if (n <=1)
                return 0;
            if (n == 2)
                return 1;
            if (n%2 == 0)
                return 0;

            int m = sqrt(n);

            for (int i=3; i <= m ; i+=2)
                if(n%i == 0)
                    return 0;
            return 1;
        }

        vector<int> getprimefactors(int num)
        {
            vector<int> primefactors;
            int i = 2;
            while (i <= num /i)
            {
                while (num % i == 0)
                {
                    num = num /i;
                    primefactors.push_back(i);
                }
                i++;
            }

            if (num > 1)
                primefactors.push_back(num);
            return primefactors;
        }

    public:
        int howMany(int A, int B) 
        {
            vector <int> factors;
            int count=0;
            for(int i = A; i <=B; i++)
            {
                factors = getprimefactors(i);
                if (isprime(factors.size()))
                    count++;
            }
            return count;
        }

};

int main(int argc, char *argv[])
{
    Underprimes up;
    cout<<up.howMany(2,10);
}

ToolsBox.cpp - On 01 Oct,2011.

#include<iostream>
#include<set>
#include<string>
#include<cstring>
#include<sstream>
#include<vector>

using namespace std;

class ToolsBox {
    public:
        int countTools(vector<string> need)
        {
            string toollist,tool;
            set<string> uniq;
            for(vector<string>::iterator it=need.begin(); it!=need.end(); ++it)
            {
                toollist = *it;
                istringstream str_of_words(toollist);
                while(str_of_words >> tool)
                    uniq.insert(tool);

            }
            return uniq.size();

        }
};

int main(int argc, char *argv[])
{
    ToolsBox obj;
    vector<string> v1;
    v1.push_back("A B C");
    v1.push_back("B C D");
    cout<<obj.countTools(v1);
}

TriFibonacci.cpp - On 01 Oct,2011.

/**

Problem : TriFibonacci

**/



#include <vector>
#include <iostream>

using namespace std;

class TriFibonacci
{
    public:
        int complete(vector <int> A)
        {
            int i,total,value;
            total = A.size();
            if (A[0] == -1)
            {
                    A[0] = A[3] - (A[2] + A[1]);
                value = A[0];
            }
            if (A[1] == -1)
            {
                A[1] = A[3] - (A[2] + A[0]);
                value = A[1];
            }
            if (A[2] == -1)
            {
                A[2] = A[3] - (A[1] + A[0]);
                value = A[2];
            }
            for (i=3; i < total; i++)
            {
                if (A[i] == -1)
                {
                    A[i] = A[i-1] + A[i-2] + A[i-3];
                    value = A[i];
                }
                else
                {
                    if (A[i] == A[i-1] + A[i-2] + A[i-3])
                        continue;
                    else
                        return -1;
                }
            }
            if (i == total)
            {
                if (value > 0)
                    return value;
                else
                    return -1;
            }
        }
};

int main(int argc, char *argv[])
{
    TriFibonacci num;
    vector <int> anum;
    anum.push_back(-1);
    anum.push_back(7);
    anum.push_back(8);
    anum.push_back(1000000);
    cout<<num.complete(anum)<<endl;
}

TheTournamentDivTwo.cpp - On 01 Oct,2011.

/* TopCoder SRM 453 Div2:
 * http://www.topcoder.com/stat?c=problem_statement&pm=10686&rd=13907
 */

#include<vector>
#include<iostream>
using namespace std;

class TheTournamentDivTwo {
    public:
        int find(vector<int> points)
        {
            int won = 0, draw = 0;
            for(vector<int>::iterator it=points.begin(); it!=points.end(); ++it)
            {
                won += (*it)/2;
                draw += (*it)%2;
            }
            if (draw%2 == 1) return -1;
            draw = draw/2;
            return won+draw;
        }
};

int main(int argc, char *argv[])
{
    TheTournamentDivTwo obj;
    vector<int> v1;
    v1.push_back(10);
    v1.push_back(1);
    v1.push_back(1);
    cout<<obj.find(v1);
}

TheProduct.cpp - On 01 Oct,2011.

#include<iostream>
#include<vector>

using namespace std;

class TheProduct {
    public:
    long long maxProduct(vector <int> numbers, int k, int maxDist)
    {
        int N,i,t,j;
        N = numbers.size();
        vector <int> newlist;
        long long max=0, result;
        for(i = 0; i < N-1;)
        {
            if (newlist.size() < k)
                newlist.push_back(i+j);
            i = maxDist;
            
            result = multiplythem(newlist,numbers);
            if (result > max)
                max = result;
        }

        return max;

    }

    long long multiplythem(vector<int> nl, vector<int> num)
    {
        long long product=1;
        for(vector<int>::iterator it=nl.begin(); it!=nl.end(); ++it)
            product *= num[*it];
        return product;
    }

};

int main(int argc, char *argv[])
{
    TheProduct obj;
    vector<int> numbers;
    int k, maxDist;
    numbers.push_back(7);
    numbers.push_back(4);
    numbers.push_back(7);
    k = 2;
    maxDist = 50;
    cout<<obj.maxProduct(numbers, k, maxDist)<<endl;

}

TheNewHouseDivTwo.cpp - On 01 Oct,2011.

#include<iostream>
#include<vector>
#include<algorithm>

using namespace std;

class TheNewHouseDivTwo{
    public:
        int count(vector <int> x, vector <int> y)
        {
            int xmin,xmax,ymin,ymax;
            vector <int> temp;
            int count;

            temp = x;
            sort(temp.begin(), temp.end());
            xmin = temp[0];
            xmax = temp[temp.size()-1];

            temp = y;
            sort(temp.begin(), temp.end());
            ymin = temp[0];
            ymax = temp[temp.size()-1];

            int i,j;
            for (i = xmin; i <=xmax; i++)
                for (j = ymin; j <=ymax; j++)
                {
                    //if i in x and j in y:

                }
        }

};

int main(int argc, char *argv[])
{
    TheNewHouseDivTwo obj;
    vector <int>x;
    vector <int>y;
    x.push_back(0);
    x.push_back(3);
    x.push_back(1);
    x.push_back(2);
    y.push_back(0);
    y.push_back(3);
    y.push_back(1);
    y.push_back(2);
    obj.count(x,y);
}

TheMoviesLevelOneDivTwo.cpp - On 01 Oct,2011.

/**

Problem Statement
    
Class: TheMoviesLevelOneDivTwo
**/

#include<vector>
#include<iostream>

using namespace std;

class TheMoviesLevelOneDivTwo
{
    public:
        int find(int n, int m, vector<int> row, vector<int> seat)
        {
            int length=0;
            int i=0;
            int j=0;
            int k=0;
            int cinema[n][m];
            int r;
            int s;
            length = row.size();
            for (i=0;i<n;i++)
                for (j=0;j<m;j++)
                    cinema[i][j] = 0;
            for (k=0;k<length;k++)
            {
                r=row[k];
                s=seat[k];
                cinema[r-1][s-1] = -1;
            }
            int count=0;
            for(i=0;i<n;i++)
                for(j=0;j<m-1;j++)
                {
                    if((cinema[i][j] == 0 ) && (cinema[i][j+1] == 0))
                        count++;
                }
            return count;
        }
};

int main(int argc, char *argv[])
{
    TheMoviesLevelOneDivTwo obj;
    vector<int> r;
    vector<int> s;
    r.push_back(1);
    s.push_back(1);
    cout<<obj.find(4,7,r,s)<<endl;
}

TheEncryptionDivTwo.cpp - On 01 Oct,2011.

#include<iostream>
#include<map>

using namespace std;

class TheEncryptionDivTwo{
    public:
        string encrypt(string message)
        {
            map<char, char> cipher;
            string alphabets = "abcdefghijklmnopqrstuvwxyz";
            string result;
            int i,j=0;
            char c,m;
            for(i=0;i<message.size();i++)
            {
                c = message[i];
                if (cipher.count(c) ==0)
                {
                    cipher[c] = alphabets[j];
                    result.push_back(alphabets[j]);
                    j++;
                }
                else
                {
                    result.push_back(cipher[c]);
                }
            }

            return result;
        }

};

int main(int argc, char *argv[])
{
    TheEncryptionDivTwo obj;
    cout<<obj.encrypt("hello");
    cout<<obj.encrypt("encryption");
}

TheCardShufflingDivTwo.cpp - On 01 Oct,2011.

#include<iostream>
#include<stack>

using namespace std;

class TheCardShufflingDivTwo
{
    public:
    int shuffle(int n, int m)
    {
        stack<int> main;
        stack<int> left;
        stack<int> right;
        int im,il,ir;
        int item,value;
        for(int i=n; i>=1; i--)
            main.push(i);

        for(int j=0; j < m; j++)
        {
            while(!main.empty())
            /**for (im=0;im<main.size(); im++) **/
            {
                item = main.top(); main.pop();
                left.push(item);
                if (!main.empty())
                {
                    item = main.top();
                    main.pop();
                    right.push(item);
                }
            }
            while (!left.empty())
            {
                item=left.top();left.pop();
                main.push(item);
            }
            
            /*
            for(il=0; il< left.size(); il++)
            {
                item = left.top();left.pop();
                main.push(item);
            }
            */
            while(!right.empty())
            {
                item=right.top();right.pop();
                main.push(item);
            }


            /**
            for(ir=0;ir < right.size(); ir++)
            {
                item = right.top(); right.pop();
                main.push(item);
            }
            **/

        }

        value = main.top();

        return value;
    }
};

int main(int argc, char *argv[])
{
    int n,m;
    n = 1000000;
    m = 1000000;
    TheCardShufflingDivTwo obj;
    cout<<obj.shuffle(n,m)<<endl;
}

TheBoredomDivTwo.cpp - On 01 Oct,2011.

#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <cmath>
using namespace std;

class TheBoredomDivTwo {
public:
    int find(int n, int m, int j, int b) {
        int res;
    if ((j + b) <= n)
        res = n;
    else
    {
        if (( j <= n) && (b > n))
            res = n +1;
        if (( b <= n) && (j > n))
            res = n +1;
        if ((j > n)  && (b > n))
            res = n +2;
    }
        return res;
    }

};

TheBlackJackDivTwo.cpp - On 01 Oct,2011.

#include<iostream>
#include<vector>
#include<cstdlib>
#include<stdio.h>

using namespace std;

class TheBlackJackDivTwo
{
    public:
        int score(vector<string> cards)
        {
            int score=0;
            int type;
            for (int i=0; i<cards.size(); i++)
            {
                type = cards[i][0];
                if (50 <= type && type <= 57)
                    score = score + (type-48);
                else if (type == 84)
                    score = score + 10;
                else if (type == 65)
                    score = score + 11;
                else if (type == 74 || type == 75 || type == 81)
                    score = score + 10;
            }
            
            return score;
        }
};

int main(int argc, char *argv[])
{
    TheBlackJackDivTwo obj;
    vector<string> v1;
    v1.push_back("4S");
    v1.push_back("7D");
    cout<<obj.score(v1);
}

TallPeople.cpp - On 01 Oct,2011.

/* TopCoder Problem Statement:
 * http://www.topcoder.com/stat?c=problem_statement&pm=2923&rd=5854
 *     
 * Class: TallPeople
 * Method: getPeople
 * Parameters: vector <string>
 * Returns: vector <int>
 * Method signature: vector <int> getPeople(vector <string> people)
 * (be sure your method is public)
 *
 */

#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
#include<cstdlib>
#include<sstream>

using namespace std;

class TallPeople {
    public:
        vector<int> getPeople(vector<string> people)
        {
            vector<int> heights,result;
            vector<vector<int> > p;
            string joined,heights_str;
            int i,j,n,r,c, tallest,shortest;
            vector<int> tallest_in_col, shortest_in_row;

            vector<string>::iterator iter;

            r = people.size();

            for(iter=people.begin(); iter!=people.end(); ++iter)
            {
                heights_str = *iter;
                
                joined.clear();
                for(i=0; i < heights_str.size(); i++)
                    joined += heights_str[i];

                istringstream str_of_numbers(joined);

                heights.clear();
                while(str_of_numbers >> n)
                {
                    heights.push_back(n);
                }
                
                p.push_back(heights);
                c = heights.size();
            }

            /* just operate on p */
            for (i = 0; i < r ; i++)
            {
                shortest = 1000000;
                for (j = 0; j < c; j++)
                    if (p[i][j] < shortest)
                        shortest = p[i][j];
                shortest_in_row.push_back(shortest);
            }
            sort(shortest_in_row.begin(), shortest_in_row.end());
            result.push_back(shortest_in_row[shortest_in_row.size()-1]);

            for (j = 0; j < c; j++)
            {
                tallest = 0;
                for (i = 0; i < r ; i++)
                    if (p[i][j] > tallest)
                        tallest = p[i][j];
                tallest_in_col.push_back(tallest);
            }
            sort(tallest_in_col.begin(), tallest_in_col.end());
            result.push_back(tallest_in_col[0]);

            return result;
        
        }
};

int main(int argc, char *argv[])
{
    TallPeople obj;
    vector<string> rc;
    vector<int> v1;
    rc.push_back("9 2 3");
    rc.push_back("4 8 7");
    v1 = obj.getPeople(rc);

    for (int i=0; i < v1.size(); i++)
        cout<<v1[i]<<endl;
}

SoccerLeagues.cpp - On 01 Oct,2011.

/**

Class: SoccerLeagues

**/

#include<iostream>
#include<vector>
#include<string>

using namespace std;

class SoccerLeagues{
    public:
        vector <int> points(vector <string> matches)
        {
            int number_of_leagues,i,j;
            number_of_leagues = matches.size();
            i= j=number_of_leagues;
            vector<int> points(number_of_leagues);
            for (i = 0; i < number_of_leagues; i++)
                for (j = 0; j < number_of_leagues; j++)
                {
                    if (matches[i][j] == 'W')
                        points[i] += 3;
                    if (matches[i][j] == 'D')
                    {
                        points[i] += 1;
                        points[j] += 1;
                    }
                    if (matches[i][j] == 'L')
                        points[j] += 3;

                }

            return points;
        }


};

int main(int argc, char *argv[])
{
    SoccerLeagues sl;
    vector<string> v1;
    vector<int> res;
    v1.push_back("-DD");
    v1.push_back("L-L");
    v1.push_back("WD-");
    res = sl.points(v1);
    for (int i =0; i< res.size(); i++)
        cout<<res[i]<<endl;

}

Starport.cpp - On 01 Oct,2011.

// BEGIN CUT HERE

// END CUT HERE
#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <cmath>
using namespace std;

vector<string> split( const string& s, const string& delim =" " ) {
    vector<string> res;
    string t;
    for ( int i = 0 ; i != s.size() ; i++ ) {
        if ( delim.find( s[i] ) != string::npos ) {
            if ( !t.empty() ) {
                res.push_back( t );
                t = "";
            }
        } else {
            t += s[i];
        }
    }
    if ( !t.empty() ) {
        res.push_back(t);
    }
    return res;
}

vector<int> splitInt( const string& s, const string& delim =" " ) {
    vector<string> tok = split( s, delim );
    vector<int> res;
    for ( int i = 0 ; i != tok.size(); i++ )
        res.push_back( atoi( tok[i].c_str() ) );
    return res;
}

// BEGIN CUT HERE
#define ARRSIZE(x) (sizeof(x)/sizeof(x[0]))

template<typename T> void print( T a ) {
    cerr << a;
}
static void print( long long a ) {
    cerr << a << "L";
}
static void print( string a ) {
    cerr << '"' << a << '"';
}
template<typename T> void print( vector<T> a ) {
    cerr << "{";
    for ( int i = 0 ; i != a.size() ; i++ ) {
        if ( i != 0 ) cerr << ", ";
        print( a[i] );
    }
    cerr << "}" << endl;
}
template<typename T> void eq( int n, T have, T need ) {
    if ( have == need ) {
        cerr << "Case " << n << " passed." << endl;
    } else {
        cerr << "Case " << n << " failed: expected ";
        print( need );
        cerr << " received ";
        print( have );
        cerr << "." << endl;
    }
}
template<typename T> void eq( int n, vector<T> have, vector<T> need ) {
    if( have.size() != need.size() ) {
        cerr << "Case " << n << " failed: returned " << have.size() << " elements; expected " << need.size() << " elements.";
        print( have );
        print( need );
        return;
    }
    for( int i= 0; i < have.size(); i++ ) {
        if( have[i] != need[i] ) {
            cerr << "Case " << n << " failed. Expected and returned array differ in position " << i << ".";
            print( have );
            print( need );
            return;
        }
    }
    cerr << "Case " << n << " passed." << endl;
}
static void eq( int n, string have, string need ) {
    if ( have == need ) {
        cerr << "Case " << n << " passed." << endl;
    } else {
        cerr << "Case " << n << " failed: expected ";
        print( need );
        cerr << " received ";
        print( have );
        cerr << "." << endl;
    }
}
// END CUT HERE
class Starport {
public:
    double getExpectedTime(int N, int M) {
        double res;
    long int maxunits = 100000;
    long int totalwait = 0;
    long int starshiptime[maxunits];
    long int teleporttime[maxunits];
    int i,j,k;
    for(i=0; i < maxunits; i++)
        starshiptime[i] = (i * M);
    for(j=0; j < maxunits; j++)
        teleporttime[j] = (j * N);
    j = 0;
    for(i=0; i < maxunits; i++)
    {
        while (starshiptime[i] <= teleporttime[j])
        {
            i++;
        }
        while (teleporttime[j] < starshiptime[i])
            j++;
        if (teleporttime[j] >= starshiptime[i])
        {
            totalwait += (teleporttime[j]-starshiptime[i]);
        }
        //else
        //  totalwait += teleporttime[j];

    }
    res = ceil((totalwait * 1.0) / maxunits);

        return res;
    }

};
// BEGIN CUT HERE
int main( int argc, char* argv[] ) {
    {
        Starport theObject;
        eq(0, theObject.getExpectedTime(4, 2),1.0);
    }
    {
        Starport theObject;
        eq(1, theObject.getExpectedTime(5, 3),2.0);
    }
    {
        Starport theObject;
        eq(2, theObject.getExpectedTime(6, 1),2.5);
    }
    {
        Starport theObject;
        eq(3, theObject.getExpectedTime(12345, 2345),6170.0);
    }
}
// END CUT HERE

SimpleWordGame.cpp - On 01 Oct,2011.

/**

Class: SimpleWordGame

**/

#include<vector>
#include<string>
#include<iostream>
#include<algorithm>
#include<cstdlib>
#include<cstring>


using namespace std;

class SimpleWordGame {

    public:
        int points(vector <string> player, vector <string> dictionary)
        {
            int score=0;
            int found=0;
            // Remove duplicates from the player.
            sort(player.begin(), player.end());
            player.erase(unique(player.begin(), player.end()),player.end());

            for (int i = 0; i < player.size(); i++)
            {
                found = 0;
                for (int j=0; j < dictionary.size(); j++)
                {
                    if (player[i] == dictionary[j])
                    {
                        found = 1;
                        score += (strlen(player[i].c_str()) * strlen(player[i].c_str()));
                        break;
                    }
                }
                if (found == 1)
                    continue;
            }

            return score;
        }
};

int main(int argc, char *argv[]){

    SimpleWordGame swg;
    vector <string> player(3), dictionary(4);
    player[0] = "apple";
    player[1] = "orange";
    player[2] = "strawberry";
    dictionary[0] = "strawberry";
    dictionary[1] = "orange";
    dictionary[2] = "grapefruit";
    dictionary[3] = "watermellon";
    cout<< swg.points(player,dictionary);
}

RoyalTresurer.cpp - On 01 Oct,2011.

/***
    
Class: RoyalTreasurer

**/


#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

class RoyalTreasurer{
    public:
        int minimalArrangement(vector <int> A, vector <int> B)
        {
            int sum = 0;
            sort(A.begin(),A.end());
            sort(B.begin(),B.end(),greater<int>());
            for (int i=0; i < A.size(); ++i)
                sum = sum + A[i] * B[i];
            return sum;
        }

};

int main(int argc, char* argv[])
{
    RoyalTreasurer rt;
    vector<int> A;
    vector<int> B;
    A.push_back(1);A.push_back(1);A.push_back(1);
    A.push_back(6);A.push_back(0);
    B.push_back(2);B.push_back(7);B.push_back(8);
    B.push_back(3);B.push_back(1);
    cout<<rt.minimalArrangement(A,B);
}

RouteIntersection.cpp - On 01 Oct,2011.

/***
  SRM 474, Round 1.

Class: RouteIntersection

**/


#include<iostream>
#include<vector>
#include<set>

using namespace std;

class RouteIntersection {
    public:
        string isValid(int N, vector <int> coords, string moves)
        {
            vector<int> start(N,0);
            set<vector<int> > setofvectors;
            int length = moves.length();
            int i;
            setofvectors.insert(start);
            for(i=0;i<length;i++)
            {
                if (moves[i] == '+')
                {
                    start[coords[i]-1] = start[coords[i]-1] + 1;
                    cout<<start[0]<<start[1]<<endl;
                }
                if (moves[i] == '-')
                {
                    start[coords[i]-1] = start[coords[i]-1] - 1;
                    cout<<start[0]<<start[1]<<endl;
                }
                if (setofvectors.count(start) > 0)
                    return "INVALID";
                setofvectors.insert(start);
            }
            return "VALID";
            //if (setofvectors.size() == length)
            //  return "VALID";
            //else
            //  return "INVALID";
        }
};

int main(int argc, char *argv[])
{
    int N=2;
    vector<int> v1;
    v1.push_back(1);
    v1.push_back(2);
    v1.push_back(1);
    v1.push_back(2);
    string s="++--";
    RouteIntersection obj;
    cout<<obj.isValid(N,v1,s)<<endl;
}

ReverseMagicalSource.cpp - On 01 Oct,2011.

#include<iostream>
#include<math.h>
using namespace std;

class ReverseMagicalSource{
    public:
        int find(int source, int A)
        {
            int i=1;
            int sum=source;
            if (source > A)
                return source;
            else
                while (sum <= A)
                {
                    source = source * (int)pow(10,i);
                    sum += source;
                }
                return sum;
        }
};

int main(int argc, char **argv)
{
    ReverseMagicalSource obj;
    cout<<obj.find(333,36963);
}

RectangularGrid.cpp - On 01 Oct,2011.

/**

  Class RectangularGrid

**/

#include <iostream>
#include <string>
#include <vector>
#include <set>
#include <map>
#include <algorithm>

using namespace std;

class RectangularGrid{

    public:
        long long countRectangles(int width, int height)
        {
            int i=0,j=0;
            long long count=0;
            for (i=1;i<=width;i++)
                for(j=1;j<=width;j++)
                {
                    if (i == j)
                        continue;
                    count += i*j;
                }
            return count;

        }
};

int main(int argc, char *argv[])
{
    RectangularGrid obj;
    cout<<obj.countRectangles(3,3)<<endl;
}

RabbitVoting.cpp - On 01 Oct,2011.

/**

Class: RabbitVoting
**/

#include <vector>
#include <iostream>
using namespace std;

class RabbitVoting {
    public:
        string getWinner(vector<string> names, vector<string> votes)
        {
            int number,i,j,vote,higgest;
            string winner;
            string name;
            number = (int)names.size();
            number = number -1;
            higgest = 0;
            for (i = 0; i <=number; i++)
            {
                name = names[i];
                vote =0;
                for(j = 0; j <=number;j++)
                    if (name.compare(votes[j]) == 0)
                        vote++;
                if (vote > higgest)
                {
                    winner = name;
                    higgest = vote;
                }
                if (vote == higgest)
                    winner = "";
            }
            return winner;
        }
        
};

int main(int argc, char *argv[])
{
    RabbitVoting obj;
    vector<string> names, votes;
    names.push_back("one");
    votes.push_back("one");
    cout<<obj.getWinner(names,votes)<<endl;
}

Quipu.cpp - On 01 Oct,2011.

/* TopCoder Problem Statement:
 * http://www.topcoder.com/stat?c=problem_statement&pm=1686&rd=4580
 *
 * Class: Quipu
 * Method:readKnots
 * Parameters: string
 * Returns:int
 * Method signature: int readKnots(string knots)
 *
 * */

#include<iostream>
#include<string>
#include<cmath>
#include<vector>

using namespace std;

class Quipu {
    public:
        int readKnots(string knots)
        {
            int c,result=0;
            vector<int> num;
            int digits=0,zeros=0;
            for(c = 1; c <(knots.size()-1);c++)
            {
                switch(knots[c])
                {
                    case 'X':
                        while(knots[c] == 'X')
                        {
                            digits++;
                            c++;
                        }
                        num.push_back(digits);
                        c--;
                        break;
                    case '-':
                        while(knots[c] == '-')
                        {
                            zeros++;
                            c++;
                        }
                        zeros -= 1;
                        if(zeros!=0)
                            while(zeros)
                            {
                                num.push_back(0);
                                zeros--;
                            }
                        c--;
                        break;
                }
                digits=0;
                zeros=0;
            }
            int digit,pos,mul;
            for(int i=0; i < num.size(); i++)
            {
                digit = num[i];
                pos = num.size()-(i+1);
                mul = power(10,pos);
                digit *= mul;
                result += digit;
            }
            return result;

        }
        int power(int base, int exp)
        {
            int p=1;
            while (exp)
            {
                p *= base;
                exp--;
            }
            return p;
        }
};

int main(int argc, char *argv[])
{
    Quipu obj;
    cout<<obj.readKnots("-XX--XXXX-XXX-")<<endl;
}

PunctuationCleaner.cpp - On 01 Oct,2011.

/***

Definition
    
Class: PunctuationCleaner
Method: clearExcess
Parameters: string
Returns: string
Method signature: string clearExcess(string document)
(be sure your method is public)

***/

#include<iostream>
#include<string>
using namespace std;

class PunctuationCleaner {
    public:
        string clearExcess(string document) {
            string::iterator it;
            string output, c, d;
            int count;
            for(it = document.begin(); it < document.end();it++)
            {
                c = *it;
                d = "";
                count = 0;
                while ((c == "!") || (c == "?"))
                {
                    if (c == "?")
                        d = c = "?";
                    it++;
                    c = *it;
                    count++;
                }
                if (d == "?")
                    output += d;
                else if (count > 0)
                    output += "!";
                output += c;
            }
            return output;
        }
};

int main(int argc, char *argv[]) {
    PunctuationCleaner obj;
    cout<<obj.clearExcess("This cheese is really great!!!!!");
}

ProfitCalculator.cpp - On 01 Oct,2011.

/**

Definition
    
Class: ProfitCalculator
Method: percent
Parameters: vector <string>
Returns: int
Method signature: int percent(vector <string> items)
(be sure your method is public)
**/
#include<iostream>
#include<sstream>
#include<vector>
#include<string>

using namespace std;

class ProfitCalculator {
    public:
        int percent(vector<string> items)
        {
            int i,total,cost=0,price=0;
            float a,b;
            string eachitem;
            total = items.size();
            for(i=0;i<total;i++)
            {
                eachitem = items[i];
                stringstream(eachitem) >> a >> b;
                price += a;
                cost += b;
            }
            return int(100 * (price-cost)/(price));

        }
};

int main(int argc, char *argv[])
{
    ProfitCalculator obj;
    vector<string> v;
    v.push_back("12.1 21.1");
    v.push_back("14.1 41.1");
    cout<<obj.percent(v);
}

PrefixCode.cpp - On 01 Oct,2011.

/**
Class: PrefixCode

**/

#include<iostream>
#include<vector>
#include<string>
#include<sstream>

using namespace std;

class PrefixCode {
    public:
        string isOne(vector <string> words)
        {
            int numofwords,i,j;
            string eachword;
            size_t found;
            string result;
            stringstream out;
            numofwords = (int) words.size();
            for( i = 0; i< numofwords; i++)
            {
                eachword = words[i];
                for (j = 0; j < numofwords; j++)
                {
                    if (i == j)
                        continue;
                    found = words[j].find(eachword);
                    if (found != string::npos)
                        if ((int)found == 0)
                        {
                            out<< i;
                            result = "No, " + out.str();
                            return result;
                        }
                }
            }
            return "Yes";
        }
};

int main(int argc, char *argv[])
{
    PrefixCode obj;
    vector <string> words;
    words.push_back("two");
    words.push_back("twosome");
    cout<<obj.isOne(words);
}

PiCalculator.cpp - On 01 Oct,2011.

/**

Class: PiCalculator

***/

/** TODO: Revisit this program after learning string, char *, const char* and other string handling methods in C++.
 * Program in the current form is very bad in the way it does string -> char -> int -> char -> string conversions.
 */

#include<iostream>
#include<cstdlib>
#include<string>

using namespace std;

class  PiCalculator {
    public: 
        string calculate(int precision) {
            string pistring ("3.141592653589793238462643383279");
            int dot = int(pistring.find('.'));
            string lastchar;
                lastchar= pistring[dot+precision];
            int value = atoi(lastchar.c_str());
            if (value > 4) ++value;
            if (value == 10) 
            {
                // Special case for rounding two digits.
                // pistring does not have consecutive 9s so I am using this dumb method.
                string laststr("0");
                string last_but_one_char;
                last_but_one_char = pistring[dot+precision-1];
                int last_but_one_value = atoi(last_but_one_char.c_str());
                ++last_but_one_value;

                char svalue[1];
                sprintf(svalue,"%d",last_but_one_value);
                string last_but_one_str;
                last_but_one_str = string(svalue);

                string slice;

                slice = pistring.substr(0,(dot+precision)-1);

                string result;

                result = slice + last_but_one_str + laststr;

                return result;

            }
            char svalue[1];
            sprintf(svalue,"%d",value);
            string lastchar_str;
            lastchar_str = string(svalue);
            string slice;
            slice = pistring.substr(0,(dot+precision));
            string result;
            result = slice + lastchar_str;
            return result;
        }
};

int main()
{
    PiCalculator piobj;
    cout<<piobj.calculate(12);
}

PassingGrade.cpp - On 01 Oct,2011.

/* TopCoder Problem Statement:
 * http://www.topcoder.com/stat?c=problem_statement&pm=1962&rd=4745
 * Definition
    
   Class: PassingGrade
   Method: pointsNeeded
   Parameters: vector <int>, vector <int>, int
   Returns: int
   Method signature: int pointsNeeded(vector <int> pointsEarned, 
                                      vector <int> pointsPossible, int finalExam)
 *  
 *  Algorithm:
 *  1. Addup all pointsPossible and finalExam.
 *  2. Take 0.65 of that total.
 *  3. Subtract pointsEarned from it. Upper of it and return it if less the
 *  value is less than finalExam else return -1
 *
 */

#include<iostream>
#include<vector>
#include<cmath>
using namespace std;

class PassingGrade {
    public:
        int pointsNeeded(vector<int> pointsEarned, vector<int> pointsPossible,
                int finalExam)
        {
            int total=0,earned=0,required,value;
            vector<int>::iterator iter;
            for(iter=pointsPossible.begin(); iter!=pointsPossible.end(); ++iter)
                total += *iter;
            total += finalExam;
            for(iter=pointsEarned.begin(); iter != pointsEarned.end(); ++iter)
                earned += *iter;
            /* The below is a good way to try idempotency with
             * float operations. Compare it both ways and settle */
            required = (65*total )/ 100 - earned;
            if (((earned+required) * 100) < (65 * total))
                required++;
            if (required > finalExam)
                return -1;
            else if (required <= 0)
                return 0;
            else
                return required;

        }
};

int main(int argc, char *argv[])
{
    PassingGrade obj;
    vector<int> v1,v2;
    v1.push_back(55);
    v1.push_back(77);
    v1.push_back(82);
    v1.push_back(60);
    v2.push_back(100);
    v2.push_back(100);
    v2.push_back(100);
    v2.push_back(100);
    cout<<obj.pointsNeeded(v1,v2,300);
}

PalindromesCount.cpp - On 01 Oct,2011.

/***

Problem Statement   PalindromesCount
**/

#include<iostream>
#include<string>
using namespace std;

class PalindromesCount {
    public:
        int ispalindrome(string C)
        {
            int i,j;
            for(i=0,j=C.length()-1; i <=j;i++,j--)
                if (C[i] != C[j])
                    return 0;
            return 1;
        }
        int count(string A, string B)
        {
            int i;
            string C;
            int count=0;
            for(i=0;i<A.length();i++)
            {
                C = A;
                C.insert(i,B);
                if (ispalindrome(C))
                    count++;
            }
            return count;
        }
};

int main(int argc, char *argv[])
{
    string A,B;
    A = "aba";
    B = "b";
    PalindromesCount obj;
    cout<<obj.count(A,B)<<endl;
}

ObtainDigitK.cpp - On 01 Oct,2011.

/**
 
Problem Statement.

SRM 367. DIV I
    
**/

#include <iostream>
#include <string>
#include <sstream>
#include <cstdlib>

using namespace std;

class ObtainDigitK {
    public:
        int minNumberToAdd(string s, int i)
        {
            string lastchar;
            string i_str;
            stringstream out;
            out << i;
            i_str = out.str();
            size_t found;
            found = s.find(i_str);
            if (found != string::npos)
                return 0;

            lastchar = s[s.length()-1];
            int lastchar_int = atoi(lastchar.c_str());
            if (lastchar_int <= i)
                return (i-lastchar_int);
            else
                return ((i+10) - lastchar_int);

        }
};

int main(int argc, char *argv[])
{
    ObtainDigitK obj;
    cout<<obj.minNumberToAdd("44",1)<<endl;
}

NoOrderOfOperations.cpp - On 01 Oct,2011.

/* TopCoder Problem Statement:
 * http://www.topcoder.com/stat?c=problem_statement&pm=2868&rd=5075
 *
 * Definition      
   Class: NoOrderOfOperations
   Method: evaluate
   Parameters: string
   Returns: int
   Method signature: int evaluate(string expr)
   (be sure your method is public)

 *
 */

#include<iostream>
#include<string>
#include<cstdlib>

using namespace std;

class NoOrderOfOperations {
    public:
        int evaluate(string expr)
        {
            int value=0;
            string c;
            for(string::iterator it=expr.begin(); it !=expr.end(); ++it)
            {
                switch(*it)
                {
                    case '+':
                        ++it;
                        c = *it;
                        value += atoi(c.c_str());
                        break;
                    case '-':
                        ++it;
                        c = *it;
                        value -= atoi(c.c_str());
                        break;
                    case '*':
                        ++it;
                        c = *it;
                        value *= atoi(c.c_str());
                        break;
                    default:
                        c = *it;
                        value += atoi(c.c_str());

                }
            }
            return value;

        }


};

int main(int argc, char *argv[])
{
    NoOrderOfOperations obj;
    cout<<obj.evaluate("2+2");
}

MostProfitable.cpp - On 01 Oct,2011.

/***

Definition
    
Class: MostProfitable
Method: bestItem
Parameters: vector <int>, vector <int>, vector <int>, vector <string>
Returns: string
Method signature: string bestItem(vector <int> costs, vector <int> prices, vector <int> sales, vector <string> items)
(be sure your method is public)

***/
#include<iostream>
#include<string>
#include<vector>

using namespace std;

class MostProfitable {
    public:
        string bestItem(vector <int> costs, vector <int> prices, vector <int> sales, vector <string> items)
        {
            int total,max=0,i,profit=0;
            string result;
            total = costs.size();
            for(i=0; i < total; i++)
            {
                profit = (prices[i] - costs[i]) * sales[i];
                if (profit > max)
                {
                    max = profit;
                    result = items[i];
                }
            }
            return result;
        }
};

MonotoneSequence.cpp - On 01 Oct,2011.

// BEGIN CUT HERE

// END CUT HERE
#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <cmath>
using namespace std;

vector<string> split( const string& s, const string& delim =" " ) {
    vector<string> res;
    string t;
    for ( int i = 0 ; i != s.size() ; i++ ) {
        if ( delim.find( s[i] ) != string::npos ) {
            if ( !t.empty() ) {
                res.push_back( t );
                t = "";
            }
        } else {
            t += s[i];
        }
    }
    if ( !t.empty() ) {
        res.push_back(t);
    }
    return res;
}

vector<int> splitInt( const string& s, const string& delim =" " ) {
    vector<string> tok = split( s, delim );
    vector<int> res;
    for ( int i = 0 ; i != tok.size(); i++ )
        res.push_back( atoi( tok[i].c_str() ) );
    return res;
}

// BEGIN CUT HERE
#define ARRSIZE(x) (sizeof(x)/sizeof(x[0]))

template<typename T> void print( T a ) {
    cerr << a;
}
static void print( long long a ) {
    cerr << a << "L";
}
static void print( string a ) {
    cerr << '"' << a << '"';
}
template<typename T> void print( vector<T> a ) {
    cerr << "{";
    for ( int i = 0 ; i != a.size() ; i++ ) {
        if ( i != 0 ) cerr << ", ";
        print( a[i] );
    }
    cerr << "}" << endl;
}
template<typename T> void eq( int n, T have, T need ) {
    if ( have == need ) {
        cerr << "Case " << n << " passed." << endl;
    } else {
        cerr << "Case " << n << " failed: expected ";
        print( need );
        cerr << " received ";
        print( have );
        cerr << "." << endl;
    }
}
template<typename T> void eq( int n, vector<T> have, vector<T> need ) {
    if( have.size() != need.size() ) {
        cerr << "Case " << n << " failed: returned " << have.size() << " elements; expected " << need.size() << " elements.";
        print( have );
        print( need );
        return;
    }
    for( int i= 0; i < have.size(); i++ ) {
        if( have[i] != need[i] ) {
            cerr << "Case " << n << " failed. Expected and returned array differ in position " << i << ".";
            print( have );
            print( need );
            return;
        }
    }
    cerr << "Case " << n << " passed." << endl;
}
static void eq( int n, string have, string need ) {
    if ( have == need ) {
        cerr << "Case " << n << " passed." << endl;
    } else {
        cerr << "Case " << n << " failed: expected ";
        print( need );
        cerr << " received ";
        print( have );
        cerr << "." << endl;
    }
}
// END CUT HERE
class MonotoneSequence {
public:
    int longestMonotoneSequence(vector <int> seq) {
        int res,i;
    int longest=1;
    int longdec=1,longinc=1;
    int len;
    len = seq.size();
    int num;
    int prev=-1;
    num = seq[0];
    for(i = 1; i < len; i++)
    {
        if ((longinc > longest) || (longdec > longest))
        {
            if (longinc >= longdec)
                longest = longinc;
            else
                longest = longdec;
        }

        if (seq[i] > num)
        {
            longdec = 0;
            if (prev == -1 || prev == 1)
            {
                longinc++;
            }
            else
            {
                longinc= 1;
            }
            prev = 1;
            num = seq[i];
        }
        if (seq[i] < num)
        {
            longinc = 0;
            if (prev == -1 || prev == 0)
            {
                longdec++;
            }
            else
            {
                longdec=1;
            }
            prev = 0;
            num = seq[i];
        }
    }

    res = longest;

        return res;
    }

};
// BEGIN CUT HERE
int main( int argc, char* argv[] ) {
    {
        int seqARRAY[] = {1, 7, 7, 8, 3, 6, 7, 2};
        vector <int> seq( seqARRAY, seqARRAY+ARRSIZE(seqARRAY) );
        MonotoneSequence theObject;
        eq(0, theObject.longestMonotoneSequence(seq),3);
    }
    {
        int seqARRAY[] = {1, 1, 1, 1, 1};
        vector <int> seq( seqARRAY, seqARRAY+ARRSIZE(seqARRAY) );
        MonotoneSequence theObject;
        eq(1, theObject.longestMonotoneSequence(seq),1);
    }
    {
        int seqARRAY[] = {10, 20, 30, 25, 20, 19, 20, 18, 23};
        vector <int> seq( seqARRAY, seqARRAY+ARRSIZE(seqARRAY) );
        MonotoneSequence theObject;
        eq(2, theObject.longestMonotoneSequence(seq),4);
    }
    {
        int seqARRAY[] = {3, 2, 1, 4};
        vector <int> seq( seqARRAY, seqARRAY+ARRSIZE(seqARRAY) );
        MonotoneSequence theObject;
        eq(3, theObject.longestMonotoneSequence(seq),3);
    }
}
// END CUT HERE

Microwaveselling.cpp - On 01 Oct,2011.

#include<iostream>
#include<string>
#include<vector>
#include<set>
#include<map>
#include<algorithm>

using namespace std;

class MicrowaveSelling {
    public:
        // method name
        int mostAttractivePrice(int minPrice, int maxPrice)
        {
            int i;
            int num, nines=0, whole=1;
            int price = maxPrice;
            num = maxPrice;

            while (num >10)
            {
                num /= 10;
                nines = (nines *10) + 9;
                whole *= 10;
            }

            for(price = maxPrice; price >= minPrice; price--)
            {
                if (whole > price)
                {
                    whole /= 10;
                    nines /= 10;
                }

                if ((price % whole) == nines)
                    return price;

            }

            return maxPrice;

        }
};

int main(int argc, char *argv[])
{
    MicrowaveSelling obj;
    cout<<obj.mostAttractivePrice(20,25)<<endl;
}

megaCool.cpp - On 01 Oct,2011.

#include<iostream>
using namespace std;

class MegaCoolNumber {
    public:
        int count(int N) {
            int megacool=0;
            // Check if N is between 1 and 1000
            if (N >=1 && N <=1000)
                for (int i = 1; i <= N; i++) {
                    if (i < 100)
                           megacool++;
                    else {
                        if (i != 1000) {
                            int d1 = i % 10;
                            int d2 = (i/10) % 10;
                            int d3 = (i/100) % 10;

                            if ((d1-d2) == (d2-d3))
                                megacool++;
                        }
                    }
                }
            return megacool;
        }

};

int main()
{
    MegaCoolNumber mnum;
    cout<<mnum.count(999);
    return 0;
}

MatrixShiftings.cpp - On 01 Oct,2011.

/***

Definition
    
Class: MatrixShiftings
Method: minimumShifts
Parameters: vector <string>, int
Returns: int
Method signature: int minimumShifts(vector <string> matrix, int value)
(be sure your method is public)

***/
#include<iostream>
#include<vector>
#include<string>
#include<sstream>
using namespace std;

class MatrixShiftings {
    public:
        int minimumShifts(vector <string> matrix, int value)
        {
            string s;
            stringstream out;
            out<<value;
            s = out.str();
            size_t found;
            int len = matrix.size();
            int j,stringlen;
            for(int i=0; i < len; i++)
            {
                found = matrix[i].find(s);
                if (found != string::npos)
                {
                    j = (int)found;
                    stringlen = matrix[i].size();
                    if (j > (stringlen-j))
                        j = stringlen-j;
                    if (i > (len-i))
                        i = len-i;
                    return i+j;

                }
            }
            return -1;

        }
};

int main(int argc, char *argv[])
{
    vector<string> v;
    v.push_back("12345");
    MatrixShiftings obj;
    cout<<obj.minimumShifts(v,4)<<endl;
}

MagicalSource.cpp - On 01 Oct,2011.

/* 
 Problem Statement      MagicalSource
*/

#include<iostream>
using namespace std;

class MagicalSource {
    long long calculate(long long x)
    {


    }
};

int main(int argc, char *argv[])
{
}

LuckyCounter.cpp - On 01 Oct,2011.

#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <cmath>
using namespace std;

class LuckyCounter {
public:
    int countLuckyMoments(vector <string> moments) {
        int res=0;
    int num = moments.size();
    string each;
    string a1,a2,b1,b2;
    for(int i=0;i<num;i++)
    {
        a1 = moments[i].substr(0,1);
        a2 = moments[i].substr(1,1);
        b1 = moments[i].substr(3,1);
        b2 = moments[i].substr(4,1);

        if ( ( (a1 == a2) && (b1 == b2)) || ((a1 == b1) && (a2 == b2)) || ((a1 == b2) && (a2 == b1)))
            res++;
    }
        return res;
    }

};

LeaguePicks.cpp - On 01 Oct,2011.

#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <cmath>
using namespace std;

class LeaguePicks {
public:
    vector <int> returnPicks(int position, int friends, int picks) {
        vector <int> res;
    int i;
    int pick;
    for (pick = 1; pick <= picks;)
    {
        for (i = 1; i <= friends; i++)
        {
            if (pick > picks)
                break;
            if (i == position)
                res.push_back(pick);
            pick++;
        }
        for (i = friends; i >=1; i--)
        {
            if (pick > picks)
                break;
            if (i == position)
                res.push_back(pick);
            pick++;
        }
    }
        return res;
    }

};

KnightsTour.cpp - On 01 Oct,2011.

/*
 * i, j is the position.
 * i - 2, j + 1
 * i - 2, j - 1
 * i - 1, j + 2
 * i - 1, j - 2
 * i + 1, j + 2
 * i + 1, j - 2
 * i + 2, j + 1
 * i + 2, j - 1
 */


#include<iostream>
#include<vector>

using namespace std;

class KnightsTour
{
    public:

    vector <pair <int, int> > validmoves(vector <string> board, int r, int c)
    {
        vector <pair <int, int> > coords;
        vector <pair <int, int> > validcoords;
        int row, col;
        coords.push_back(make_pair(2,1));
        coords.push_back(make_pair(2,-1));
        coords.push_back(make_pair(1,2));
        coords.push_back(make_pair(1,-2));
        coords.push_back(make_pair(-1,2));
        coords.push_back(make_pair(-1,-2));
        coords.push_back(make_pair(-2,1));
        coords.push_back(make_pair(-2,-1));

        for(int i=0; i < coords.size(); i++)
        {
            row = r + coords[i].first;
            col = c + coords[i].second; 
            if ( (0 <= row) && (row < board.size()) && (0 <= col) && (col < board.size()) )
            {
                if (board[row][col] == '.')
                    validcoords.push_back(make_pair(row,col));
            }
        }
        return validcoords;

    }

    int visitedPositions(vector <string> board)
    {
        int r,c,i,j,pos, nr,nc;
        vector <pair <int, int> > validcoords, possiblemoves;
        int visited=0,smallest=8,nextmoves=0;
        for (i = 0; i < board.size(); i++)
        {
            pos = board[i].find("K");
            if(pos != -1)
            {
                r = i;
                c = pos;
            }
        }

        do
        {
        board[r][c] = '*'; visited++;
        validcoords = validmoves(board, r,c);
        nextmoves = validcoords.size();
        smallest = 8;
        for (j=0; j < nextmoves; j++)
        { 
            possiblemoves = validmoves(board, validcoords[j].first, validcoords[j].second);
            if (possiblemoves.size() <= smallest)
            {
                smallest = possiblemoves.size();
                nr = validcoords[j].first;
                nc = validcoords[j].second;
            }

        }
        if (nextmoves > 0)
        {
            r = nr;
            c = nc;
        }

        }while(nextmoves > 0);

        return visited;
    }

};
int main(int argc, char *argv[])
{
    KnightsTour obj;
    vector <string> board;
    board.push_back("K.......");
    board.push_back("........");
    board.push_back("........");
    board.push_back("........");
    board.push_back("........");
    board.push_back("........");
    board.push_back("........");
    board.push_back("........");
    cout<<obj.visitedPositions(board)<<endl;
}

KiwiJuice.cpp - On 01 Oct,2011.

/**

Definition
    
Class: KiwiJuiceEasy
Method: thePouring
Parameters: vector <int>, vector <int>, vector <int>, vector <int>
Returns: vector <int>
Method signature: vector <int> thePouring(vector <int> capacities, vector <int> bottles, vector <int> fromId, vector <int> toId)
(be sure your method is public)

**/

#include<iostream>
#include<vector>
using namespace std;

class KiwiJuiceEasy {
    public:
        vector <int> thePouring(vector <int> capacities, vector <int> bottles, vector <int> fromId, vector <int> toId)
        {
            int i,total,mj,f,t,m,ac,rem;
            total = fromId.size();
            for(i = 0; i <total; i++)
            {
                f = fromId[i];
                t = toId[i];
                mj = bottles[f];
                ac = capacities[t] - bottles[t];

                if (mj <= ac)
                {
                    bottles[f] = bottles[f] - mj;
                    bottles[t] = bottles[t] + mj;
                }
                else
                {
                    bottles[f] = bottles[f] - ac;
                    bottles[t] = bottles[t] + ac;

                }
            }
            return bottles;
        }
};

incredibleMachine.cpp - On 01 Oct,2011.

/***

Problem Statement
    
You may remember an old computer game called "The Incredible Machine". It was a
game where you could simulate simple processes like balls falling, lasers
shooting, or cats pursuing mice. Moreover, you were able to perform these
observations with different values for gravitational acceleration.  Imagine a
system with some unknown acceleration of gravity. There are N balls, each fixed
initially at some height above the ground. You are given a vector <int> height,
where the i-th element is the height of the i-th ball above the ground. At time
0, the first ball is set loose and it starts falling. When it reaches the
ground, the second ball is instantly set loose, and so on. This continues until
the last ball reaches the ground at time T.  Return the acceleration of gravity
in this system. Neglect air resistance and any other resisting factors. The
distance d travelled by an object falling for time t with no initial velocity
in a system with gravitational acceleration g and no resisting factors is equal
to d = 0.5 * g * t^2.

Definition
    
Class:
IncredibleMachineEasy
Method:
gravitationalAcceleration
Parameters:
vector <int>, int
Returns:
double
Method signature:
double gravitationalAcceleration(vector <int> height, int T)
    (be sure your method is public)
        

    Constraints
    -
    height will contain between 1 and 50 elements, inclusive.
    -
    Each element of height will be between 1 and 100, inclusive.
    -
    T will be between 1 and 100, inclusive.
    Examples
    0)

        
{16,23,85,3,35,72,96,88,2,14,63}
30
Returns: 9.803799620759717
That's an acceleration of gravity that might be somewhere on Earth's surface.
1)

    
{6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,5}
12
Returns: 26.73924541044107
And this is likely on Jupiter.
2)

    
{8,8}
3
Returns: 7.111111111111111
That's a light one.
3)

    
{3,1,3,1,3}
12
Returns: 0.7192306901503684
You could nearly fly under such conditions.

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2003, TopCoder, Inc. All rights reserved.
***/

#include<math.h>
#include<algorithm>
#include<vector>
#include<iostream>
#include<iomanip>

using namespace std;

class IncredibleMachineEasy {

    public:

    double gravitationalAcceleration(vector <int> height, int T)
    {
        double gravity;
        double sumsq2ds=0.0;
        for (int i =0; i < height.size(); i++) {
            sumsq2ds = sumsq2ds + sqrt(2.0*height[i]);
        }
        gravity = (sumsq2ds * sumsq2ds) / (T*T);

        return gravity;

    }

};

int main()
{
    IncredibleMachineEasy gravity;
    vector<int> values;
    values.push_back(3);
    values.push_back(1);
    values.push_back(3);
    values.push_back(1);
    values.push_back(3);
    cout<<setprecision(12);
    cout << gravity.gravitationalAcceleration(values,12) <<endl;
}

GuessingNextElement.cpp - On 01 Oct,2011.

#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <cmath>
using namespace std;

class GuessingNextElement {
public:
    int guess(vector <int> A) {
    int p, q, last, secondlast,n;
        int res;
    p = A[0];
    last = A[A.size()-1];
    secondlast = A[A.size()-2];

    if (last % secondlast == 0)
    {
        n = last / secondlast;
        if ((p * n) == A[1])
            res = last * n;
        else
        {
            n = last - secondlast;
            if ((p + n) == A[1])
                res = last + n;
        }
    }
    else
    {
        n = last - secondlast;
        res = last + n;
    }
        return res;
    }

};

ImportantTasks.cpp - On 01 Oct,2011.

#include<iostream>
#include<vector>
#include<algorithm>

using namespace std;

class ImportantTasks
{
    public:
        int maximalCost(vector <int> complexity, vector <int> computers)
        {
            sort(complexity.begin(), complexity.end());
            sort(computers.begin(), computers.end());
            int count=0;
            for (int i=0; i < computers.size(); i++)
                for (int j=0; j< complexity.size(); j++)
                    if (complexity[j] <= computers[i])
                    {
                        count++;
                        complexity[j] = 1000001;
                        break;
                    }
            return count;
        }
};

ImageDithering.cpp - On 01 Oct,2011.

/* SRM 145 Div 2 200
 *     
 * Class: ImageDithering
 * Method: count
 * Parameters: string, vector <string>
 * Returns: int
 * Method signature: int count(string dithered, vector <string> screen)
 *
 */

#include<iostream>
#include<string>
#include<vector>
using namespace std;

class ImageDithering {
    public:
        int count(string dithered, vector<string> screen)
        {
            int result=0;
            string::iterator str_iter;
            for(vector<string>::iterator iter=screen.begin();
                    iter != screen.end(); ++iter)
            {
                for(str_iter = (*iter).begin();
                        str_iter != (*iter).end();
                        ++str_iter)
                {
                    if (dithered.find(*str_iter) != string::npos)
                        result++;
                }

            }
            return result;


        }
};

int main(int argc, char *argv[])
{
    ImageDithering obj;
    vector<string> v1;
    v1.push_back("AAAA");
    v1.push_back("BBBB");
    cout<< obj.count("XB",v1)<<endl;
}

Graduation_SnapDragon.cpp - On 01 Oct,2011.

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <functional>
#include <numeric>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <queue>
using namespace std;
typedef vector<int> VI;  typedef vector<vector<int> > VVI;
typedef vector<string> VS;  typedef vector<vector<string> > VVS;
typedef signed long long i64;  typedef unsigned long long u64;

int taken[128];

// NOTE: returns -1 for unmatched items.  nm is number of matchable items.
int bipartitematch(const vector<vector<int> > &m, int nm = 128) {
  vector<int> mat(nm, -1), ret(m.size(), -1);
  int i, j, x, y;
  int retn = 0;

  for( i = 0; i < m.size(); i++ ) {
    queue<int> q;
    vector<int> pred(m.size(), -1);
    q.push(i);
    pred[i] = -2;
    while( !q.empty() ) {
      x = q.front(); q.pop();
      for( j = 0; j < m[x].size(); j++ ) if( taken[m[x][j]] ) {
    cout<<m[x][j]<<endl;
        y = mat[m[x][j]];
        if( y == -1 ) goto found;
        if( pred[y] != -1 ) continue;
        pred[y] = x;
        q.push(y);
      }
    }
    continue;
found:  y = m[x][j];
    retn++;
    while( x != -2 ) {
      mat[y] = x;
      swap(ret[x], y);
      x = pred[x];
    }
  }
  return retn;
}

class Graduation {
public:
string moreClasses(string a, vector <string> b) {
  int i, j, k, x, y, z, n;
  string ret = "";
  VVI m;

  for( i = 0; i < b.size(); i++ ) {
    n = atoi(b[i].c_str());
    for( j = 0; j < n; j++ ) {
      m.push_back(VI());
      for( k = 0; k < b[i].size(); k++ ) if( !isdigit(b[i][k]) )
        m.back().push_back(b[i][k]);
    }
  }
  if( m.size() > 128 ) return "0";
  for( i = 0; i < a.size(); i++ ) taken[a[i]] = 1;
  n = m.size()-bipartitematch(m);
  x = 33;
  while( n ) {
    if( x >= 128 ) return "0";
    if( taken[x] ) {x++; continue;}
    taken[x] = 1;
    if (x >= 67)
        cout<<x;
    z = m.size()-bipartitematch(m);
    if( z == n )
      taken[x] = 0;
    else
      ret += x;
    n = z;
    x++;
  }
  return ret;
}
}; 
int main(int argc, char *argv[])
{
    string a="A";
    vector <string> b;
    Graduation obj;
    b.push_back("2ABC");
    b.push_back("2DEF");
    cout<< obj.moreClasses(a,b);
}

GirlsAndBoys.cpp - On 01 Oct,2011.

/***

Problem Statement: GirlsAndBoys
    

Algorithm:
1. Imitate bubble sort.
2. Two loops and in the inner loop, count the swaps for boys and girls.
2. Whoever is lesser their swap number will be the result.
***/

#include<iostream>
#include<string>
#include<vector>
#include<set>
#include<map>
#include<algorithm>

using namespace std;

class  GirlsAndBoys{
    public:
        // method name
        int sortThem(string row)
        {
            int i=0,j=0,b=0,g=0;
            for(i=0; i < row.size(); i++)
                for(j = 0; j < i; j++)
                {
                    b += row[i] < row[j];
                    g += row[i] > row[j];
                }
            return b < g? b:g;
        }
};

int main(int argc, char *argv[])
{
    GirlsAndBoys obj;
    cout<<obj.sortThem("BBGGGGGB");
}

FormatAmt.cpp - On 01 Oct,2011.

/**

Problem Statement: FormatAmt
    
**/

#include <iostream>
#include <string>
#include <stdlib.h>

using namespace std;

class FormatAmt {

    public:
        string amount(int dollars, int cents)
        {
            string result;
            string reversedstr;
            string centsval = ".";
            string finalresult;
            int digit;
            char c;
            int count=0;
            while(dollars > 9)
            {
                digit = dollars - ((dollars/10) * 10);
                c = (char) (48 + digit);
                result += c;
                dollars /= 10;
                count++;
                if (count %3 == 0) result += ",";
            }
            c = (char) (48 + dollars);
            result += c;
            result += "$";
            for(string::iterator it = result.end();
                    it != result.begin();
                    it--)
            {
                c = *it;
                reversedstr.push_back(c);
            }
            c = result[0];
            reversedstr.push_back(c);
            if (cents == 0)
            {
                centsval += "00";
                finalresult = reversedstr + centsval;
                return finalresult;
            }
            if (cents < 10)
            {
                c = (char) (48 + cents);
                centsval += "0";
                centsval += c;
                finalresult = reversedstr + centsval;
                return finalresult;
            }
            string centsdigits;
            while (cents > 0)
            {
                digit = cents - ((cents/10) * 10);
                c = (char) (48 + digit);
                centsdigits += c;
                cents /= 10;
            }
            centsval += centsdigits[1];
            centsval += centsdigits[0];
            finalresult = reversedstr + centsval;
            return finalresult;
        }

};

int main(int argc, char *argv[])
{
    FormatAmt obj;
    cout<<obj.amount(1000009,10)<<endl;
}

FixedPointTheorem.cpp - On 01 Oct,2011.

/**

One simple function that does this is the logistic function F(X)=R*X*(1-X) in
the interval [0,1] for certain values of R. For example, if you start with the
value X=.25 and feed it into F to get a new X, then feed that value into F to
get yet another X, and so on, the values of X that are produced will converge
to a small set of values that will eventually repeat forever, called a cycle.
Your program will be given a double R between 0.1 and 3.569 inclusive. Starting
with X=.25, generate the first 200,000 iterations of F using the given value of
R, which will stabilize values of X. Then generate 1000 more values, and return
the range of these values (highest value - lowest value). In other words, you
will be finding the range of the values produced between iterations 200,001 and
201,000 inclusive.

Definition
    
Class: FixedPointTheorem
Method: cycleRange
Parameters: double
Returns: double
Method signature: double cycleRange(double R)

- R will be a value between 0.1 and 3.569 inclusive.
- R will always be a value such that the process stated above will produce a result accurate to 1e-9 (absolute or relative).

Examples
0)
    
0.1
Returns: 0.0
At low numbers, there exists only one point in the cycle, so the answer is 0.0.

1)
    
3.05
Returns: 0.14754098360655865

**/

#include<iostream>
using namespace std;

class FixedPointTheorem {
    public:
        double cycleRange(double R)
        {
            int i;
            double X, high, low,result;
            X=0.25;
            for (i=0;i<200000;i++)
            {
                X = R*X*(1-X);
            }
            high = low = X;
            for(i=0;i<1000;i++)
            {
                X = R*X*(1-X);
                if (X < low) low = X;
                if (X > high) high = X;
            }
            result = (double)high-low;
            return result;
        }
};

int main(int argc, char *argv[])
{
    FixedPointTheorem obj;
    cout<<obj.cycleRange(0.1)<<endl;
    cout<<obj.cycleRange(3.05)<<endl;
}

FallingPoints.cpp - On 01 Oct,2011.

#include<math.h>
#include<algorithm>
#include<vector>
#include<iostream>

using namespace std;

class FallingPoints {
    public:
        vector <double> getHeights(vector <int> X, int R) {
            vector <double> ans;
            ans.push_back(0.0);

            for (int i=1; i < (int)X.size(); ++i)
            {
                double x1 = X[i-1], y1=ans[i-1], x2 = X[i];
                double y2;

                if ((x2-x1) * (x2-x1) > R*R)
                    ans.push_back(0.0);
                else {
                    y2 = sqrt(R*R - (x2-x1) * (x2-x1)) + y1;
                    ans.push_back(y2);
                }
            }
            return ans;
        }
};

int main()
{
    FallingPoints fps;
    vector<int> xcords;
    vector<double> answer;
    xcords.push_back(10);
    xcords.push_back(100);
    answer = fps.getHeights(xcords,10);
    for (int i=0; i < (int) answer.size(); ++i)
        cout<<answer[i];
}

EggCartons.cpp - On 01 Oct,2011.

// BEGIN CUT HERE

// END CUT HERE

#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <cmath>

using namespace std;

vector<string> split(const string& s, const string& delim = " ") {
        vector<string> res;
        string t;
        for ( int i = 0 ; i != s.size() ; i++ ) {
             if ( delim.find( s[i] ) != string::npos ) {
                if ( !t.empty() ) {
                     res.push_back(t);
                     t = "";
                }
             } else {
                 t += s[i];
             }
         }
         if ( !t.empty() ) {
              res.push_back(t);
         }
         return res;
}

vector<int> splitInt( const string& s, const string& delim = " ") {
    vector<string> tok = split (s, delim);
    vector<int> res;
    for ( int i = 0; i != tok.size(); i++ )
         res.push_back( atoi ( tok[i].c_str() ) );
    return res;
}

// BEGIN CUT HERE

#define ARRSIZE(x)  (sizeof(x) / sizeof(x[0]))

template<typename T> void print(T a) {
     cerr << a;
}
static void print (long long a) {
     cerr << a << "L";
}
static void print( string a) {
     cerr << '"' << a << '"';
}
template<typename T> void print( vector<T> a) {
     cerr << "{";
     for ( int i = 0; i != a.size(); i++ ) {
          if ( i != 0 ) cerr << ", ";
          print( a[i] );
     }
     cerr << "}" << endl;
}
template<typename T> void eq(int n, T have, T need) {
     if ( have == need) {
        cerr << "Case " << n << " passed. " << endl;
     } else {
        cerr << "Case " << n <<"  failed: expected ";
        print( need);
        cerr << "received ";
        print (have);
        cerr << "." << endl;
     }
}

template<typename T> void eq(int n, vector<T> have, vector<T> need) {
    if ( have.size() != need.size() ) {
      cerr << "Case " << n << " failed: returned " << have.size() << " elements; expected " << need.size() << " elements.";
      print( have);
      print (need);
      return;
    }
    for (int i= 0; i < have.size(); i++ ) {
         if (have[i] != need[i] ) {
            cerr << "Case " << n << "failed: returned " << have.size() << "elements; expected " << need.size() << "elements.";
            print (have);
            print (need);
            return;
         }
         for ( int i=0; i < have.size(); i++) {
             if (have[i] != need[i] ) {
                 cerr << "Case " << n << " failed. Expected and returned array differ in position " << i << ".";
                 print (have);
                 print (need);
                 return;
             }
         }
         cerr <<"Case " << n << " passed." << endl;
    }
}

static void eq(int n, string have, string need) {
        if ( have == need) {
           cerr << "Case " << n << " passed." << endl;
       } else {
           cerr << "Case " << n << " failed: expected ";
           print( need );
           cerr << " received";
           print( have );
           cerr << "." << endl;
      }
}
// END CUT HERE

class EggCartons {
public:
         int minCartons(int n) {
                   int res;
                   res = 42;
                   return res;
          }

};
// BEGIN CUT HERE
int main(int argc, char* argv[] ) {
    {
        EggCartons theObject;
        eq(0, theObject.minCartons(20),3);
    }
    {
        EggCartons theObject;
        eq(1, theObject.minCartons(24),3);
    }
    {
        EggCartons theObject;
        eq(2, theObject.minCartons(15),-1);
    }
    {
        EggCartons theObject;
        eq(3, theObject.minCartons(4),-1);
    }
}
// END CUT HERE

DivisorDigits.cpp - On 01 Oct,2011.

/**

Problem Statement: DivisorDigits
    
*/

#include <iostream>
#include <string>
#include <vector>
#include <set>
#include <map>
#include <algorithm>

using namespace std;

class DivisorDigits {
    public:
        int howMany(int number)
        {
            int orig=number;
            int count=0,digit;
            while (number)
            {
                digit = number - ((number/10)*10);
                number = number/10;
                if ((orig % digit) == 0)
                    count++;
            }
            return count;
            
        }
};

int main(int argc, char *argv[])
{
    DivisorDigits obj;
    cout<<obj.howMany(12345)<<endl;
}

DiscSpace.cpp - On 01 Oct,2011.

/***

Definition
    
Class: DiskSpace
Method: minDrives
Parameters: vector <int>, vector <int>
Returns: int
Method signature: int minDrives(vector <int> used, vector <int> total)
(be sure your method is public)
***/
#include<iostream>
#include<vector>
#include<algorithm>
#include<numeric>

using namespace std;

class DiskSpace {
    public:
        int minDrives(vector<int> used, vector<int> total)
        {
            sort(used.begin(),used.end());
            sort(total.begin(), total.end());
            reverse(total.begin(), total.end());
            int i,j,ts;
            ts = total.size();
            int capacity;
            capacity = accumulate(used.begin(),used.end(),0);

            for(i=0;i<ts;i++)
            {
                capacity -= total[i];
                if (capacity <= 0) break;
            }
            return i+1;
        }
};
int main(int argc, char *argv[])
{
    DiskSpace obj;
}

CCipher.cpp - On 01 Oct,2011.

/* TopCoder Problem Statement:
   http://www.topcoder.com/tc?module=ProblemDetail&rd=4540&pm=1667

Class: CCipher
Method: decode
Parameters: string, int
Returns: string
Method signature: string decode(string cipherText, int shift)
 

*/

#include<iostream>
#include<string>
using namespace std;

class CCipher {
    public:
        string decode(string cipherText, int shift)
        {
            int c;
            string result;
            for(string::iterator it=cipherText.begin(); 
                    it !=cipherText.end();
                    ++it)
            {
                c = *it;
                if ((c-shift) < 65)
                    result.push_back(c-shift+26);
                else
                    result.push_back(c-shift);
            }

            return result;
                    
        }
};

int main(int argc, char *argv[])
{
    CCipher obj;
    cout<<obj.decode("VQREQFGT",2);

}

CarrotJumping.cpp - On 01 Oct,2011.

/**

Problem Statement: CarrotJumping
    
Definition
    
Class: CarrotJumping
Method: theJump
Parameters: int
Returns: int
Method signature: int theJump(int init)
(be sure your method is public)

*/

#include<iostream>
using namespace std;

class CarrotJumping {
    public:
        int theJump(int init)
        {
            int n,np,a,b;
            np = init;
            if ((np % 1000000007) == 0)
                return n;
            for(n = 0; n < 100000; n++)
            {
                a = (4 * np) + 3;
                if ((a % 1000000007) == 0)
                {
                    return n+1;
                }
                b = (8 * np) + 7;
                if (( b % 1000000007) == 0)
                {
                    return n+1;
                }
                if ((a % 1000000007)< (b % 1000000007))
                    np = a;
                else
                    np = b;
            }

        }
};

int main(int argc, char *argv[])
{

}

BoxesOfBooks.cpp - On 01 Oct,2011.

#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <cmath>
using namespace std;

vector<string> split( const string& s, const string& delim =" " ) {
    vector<string> res;
    string t;
    for ( int i = 0 ; i != s.size() ; i++ ) {
        if ( delim.find( s[i] ) != string::npos ) {
            if ( !t.empty() ) {
                res.push_back( t );
                t = "";
            }
        } else {
            t += s[i];
        }
    }
    if ( !t.empty() ) {
        res.push_back(t);
    }
    return res;
}

vector<int> splitInt( const string& s, const string& delim =" " ) {
    vector<string> tok = split( s, delim );
    vector<int> res;
    for ( int i = 0 ; i != tok.size(); i++ )
        res.push_back( atoi( tok[i].c_str() ) );
    return res;
}

// BEGIN CUT HERE
#define ARRSIZE(x) (sizeof(x)/sizeof(x[0]))

template<typename T> void print( T a ) {
    cerr << a;
}
static void print( long long a ) {
    cerr << a << "L";
}
static void print( string a ) {
    cerr << '"' << a << '"';
}
template<typename T> void print( vector<T> a ) {
    cerr << "{";
    for ( int i = 0 ; i != a.size() ; i++ ) {
        if ( i != 0 ) cerr << ", ";
        print( a[i] );
    }
    cerr << "}" << endl;
}
template<typename T> void eq( int n, T have, T need ) {
    if ( have == need ) {
        cerr << "Case " << n << " passed." << endl;
    } else {
        cerr << "Case " << n << " failed: expected ";
        print( need );
        cerr << " received ";
        print( have );
        cerr << "." << endl;
    }
}
template<typename T> void eq( int n, vector<T> have, vector<T> need ) {
    if( have.size() != need.size() ) {
        cerr << "Case " << n << " failed: returned " << have.size() << " elements; expected " << need.size() << " elements.";
        print( have );
        print( need );
        return;
    }
    for( int i= 0; i < have.size(); i++ ) {
        if( have[i] != need[i] ) {
            cerr << "Case " << n << " failed. Expected and returned array differ in position " << i << ".";
            print( have );
            print( need );
            return;
        }
    }
    cerr << "Case " << n << " passed." << endl;
}
static void eq( int n, string have, string need ) {
    if ( have == need ) {
        cerr << "Case " << n << " passed." << endl;
    } else {
        cerr << "Case " << n << " failed: expected ";
        print( need );
        cerr << " received ";
        print( have );
        cerr << "." << endl;
    }
}
// END CUT HERE
class BoxesOfBooks {
public:
    int boxes(vector <int> weights, int maxWeight) {
        int res;
    int num,cur,rem;
    num = weights.size();
    int total=0;
    for(int i=0; i <=num; i++)
    {
        cur = weights[i];
        rem = maxWeight;
        while (cur <= rem)
        {
            rem -= cur;
            i+= 1;
            cur = weights[i];
        }
        total++;
    }

        return total;
    }

};
// BEGIN CUT HERE
int main( int argc, char* argv[] ) {
    {
        int weightsARRAY[] = { 5, 5, 5, 5, 5, 5 };
        vector <int> weights( weightsARRAY, weightsARRAY+ARRSIZE(weightsARRAY) );
        BoxesOfBooks theObject;
        eq(0, theObject.boxes(weights, 10),3);
    }
    {
        int weightsARRAY[] = { 51, 51, 51, 51, 51 };
        vector <int> weights( weightsARRAY, weightsARRAY+ARRSIZE(weightsARRAY) );
        BoxesOfBooks theObject;
        eq(1, theObject.boxes(weights, 100),5);
    }
    {
        int weightsARRAY[] = { 1, 1, 1, 7, 7, 7 };
        vector <int> weights( weightsARRAY, weightsARRAY+ARRSIZE(weightsARRAY) );
        BoxesOfBooks theObject;
        eq(2, theObject.boxes(weights, 8),4);
    }
    {
        int weightsARRAY[] = { 12, 1, 11, 2, 10, 3, 4, 5, 6, 6, 1 };
        vector <int> weights( weightsARRAY, weightsARRAY+ARRSIZE(weightsARRAY) );
        BoxesOfBooks theObject;
        eq(3, theObject.boxes(weights, 12),6);
    }
    {
        BoxesOfBooks theObject;
        eq(4, theObject.boxes(vector <int>(), 7),0);
    }
    {
        int weightsARRAY[] = { 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
             20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
             20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
             20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
             20, 20, 20, 20, 20, 20, 20, 20, 20, 20 };
        vector <int> weights( weightsARRAY, weightsARRAY+ARRSIZE(weightsARRAY) );
        BoxesOfBooks theObject;
        eq(5, theObject.boxes(weights, 1000),1);
    }
}
// END CUT HERE

BoredPhilosophers.cpp - On 01 Oct,2011.

/** Problem Statement:
 * http://www.topcoder.com/stat?c=problem_statement&pm=10456
 * */

#include<iostream>
#include<vector>
#include<string>
#include<set>
#include<cstring>
#include<sstream>

using namespace std;

class BoredPhilosophers {
    public:
        vector <int> simulate(vector <string> text, int N)
        {
            vector <int> v1;
            vector <string> words;
            string joined,aword,group_of_words;
            set <string> uniq;
            int i,j,k, word_length;

            for(i=0; i < text.size(); i++)
                joined += text[i];

            cout<<joined<<endl;
            istringstream str_of_words(joined);

            while (str_of_words >> aword)
                words.push_back(aword);

            for(i=0; i<N;i++)
            {
                uniq.clear();
                for (j=0; j < words.size(); j++)
                {
                    word_length = i+1;
                    if ((j + word_length) > words.size())
                        break;
                    group_of_words.clear();
                    for(k=j;k<(j+word_length);k++)
                        group_of_words += words[k];
                    uniq.insert(group_of_words);
                }
                v1.push_back(uniq.size());
            }

            return v1;
        }
};

int main(int argc, char **argv)
{
    BoredPhilosophers obj;
    vector <string> v1;
    vector <int> out;
    v1.push_back("hello world");
    out = obj.simulate(v1,2);
    for(int i=0;i<out.size();i++)
        cout<<out[i]<<endl;
}

Bonuses.cpp - On 01 Oct,2011.

/**

Problem Statement: Bonuses.cpp
    
**/

#include <vector>
#include <iostream>
#include <algorithm>

using namespace std;

class Bonuses {
    public:
        vector <int> getDivision(vector <int> points)
        {
            int count;
            int i;
            int total = 0;
            count = (int)points.size();
            for(i=0; i< count; ++i)
                total = total + points[i];

            vector <int> ans;
            for(i = 0; i < count ; ++i)
            {
                int share = ((points[i] * 1.0)/ total) * 100;
                ans.push_back(share);
            }

            int distributed = 0;

            for(i = 0; i< count ; ++i)
                distributed += ans[i];

            int remaining = 100 - distributed;

            //cout<<remaining<<"points remaining"<<endl;

            vector <int> sortedans;
            sortedans = ans;
            stable_sort(sortedans.begin(), sortedans.end());

            int topscorers[remaining];
            int j =0;
            int scoredistribution = remaining;

            for(i=int(sortedans.size())-1;scoredistribution>=0; --i, --scoredistribution)
                topscorers[j++] = sortedans[i];

            //for(i=0; i<remaining;++i)
                //cout<<topscorers[i]<<endl;
            int toassign = 0;

            for(i=0; i< remaining;++i)
            {
                toassign = topscorers[i];
                for(j=0;j < (int)ans.size();++j)
                    if (ans[j] == toassign)
                    {
                        ans[j] += 1;
                        break;
                    }
            }
            return ans;
        }

};

int main()
{
    Bonuses bon;
    vector <int> pointstopass;
    vector <int> answer;
    pointstopass.push_back(5);
    pointstopass.push_back(5);
    pointstopass.push_back(5);
    pointstopass.push_back(5);
    pointstopass.push_back(5);
    pointstopass.push_back(5);
    /**
    pointstopass.push_back(5);
    pointstopass.push_back(4);
    pointstopass.push_back(3);
    pointstopass.push_back(4);
    pointstopass.push_back(2);
    pointstopass.push_back(4);
    pointstopass.push_back(1);
    **/
    answer = bon.getDivision(pointstopass);
    for(int i=0; i<(int)answer.size(); ++i)
        cout<<answer[i]<<endl;
}

BinaryCode.cpp - On 01 Oct,2011.

/**

ProblemName: BinaryCode

**/

#include<iostream>
#include<string>
#include<vector>
#include<cstdlib>

using namespace std;

class BinaryCode {

    public:
        vector<string> decode(string message){

            vector<string> result;
            string P0,P1,Q;
            Q = message;

            int len = Q.size();
            int i;

            P0 = "0";
            for (i = 0; i < len; ++i)
            {
                if ((i-1) < 0)
                {
                    // Q[i] = P0[i] + P0[i+1]
                    string p0,q;
                    p0 = P0[i];
                    q = Q[i];

                    int q1 = atoi(p0.c_str());
                    int q2 = atoi(q.c_str());

                    int p = q2-q1;

                    if ( (p < 0) || (p > 1))
                    {
                        result.push_back("NONE");
                        break;
                    }
                    if (p == 0) P0 += "0";
                    if (p == 1) P0 += "1";

                }
                else if ((i+1) == len)
                {
                    // Verify: Q[i] = P0[i-1] + P[i]
                    string p0,p,q;
                    p0 = P0[i-1];
                    p = P0[i];
                    q = Q[i];
                    int q0 = atoi(p0.c_str());
                    int q1 = atoi(p.c_str());
                    int q2 = atoi(q.c_str());
                    if (q2 == (q1 + q0)) 
                        result.push_back(P0);
                    else 
                        result.push_back("NONE");
                }
                else
                {

                    //Q[i] = P0[i-1] + P0[i] + P0[i+1];
                    string p0,p1,q;
                    p0 = P0[i-1];
                    p1 = P0[i];
                    q  = Q[i];
                    int q1 = atoi(p0.c_str());
                    int q2 = atoi(p1.c_str());
                    int q3 = atoi(q.c_str());
                    int p = q3 - (q1 + q2);
                    if ((p < 0) || (p > 1))
                    {
                        result.push_back("NONE");
                        break;
                    }
                    if (p == 0) P0 += "0";
                    if (p == 1) P0 += "1";

                }
            }

            P0 = "1";
            for (i = 0; i < len; ++i)
            {
                if ((i-1) < 0)
                {
                    // Q[i] = P0[i] + P0[i+1]
                    string p0,q;
                    p0 = P0[i];
                    q = Q[i];

                    int q1 = atoi(p0.c_str());
                    int q2 = atoi(q.c_str());

                    int p = q2-q1;

                    if ( (p < 0) || (p > 1))
                    {
                        result.push_back("NONE");
                        break;
                    }
                    if (p == 0) P0 += "0";
                    if (p == 1) P0 += "1";

                }
                else if ((i+1) == len)
                {
                    // Verify: Q[i] = P0[i-1] + P[i]
                    string p0,p,q;
                    p0 = P0[i-1];
                    p = P0[i];
                    q = Q[i];
                    int q0 = atoi(p0.c_str());
                    int q1 = atoi(p.c_str());
                    int q2 = atoi(q.c_str());
                    if (q2 == (q1 + q0)) 
                        result.push_back(P0);
                    else 
                        result.push_back("NONE");
                }
                else
                {

                    //Q[i] = P0[i-1] + P0[i] + P0[i+1];
                    string p0,p1,q;
                    p0 = P0[i-1];
                    p1 = P0[i];
                    q  = Q[i];
                    int q1 = atoi(p0.c_str());
                    int q2 = atoi(p1.c_str());
                    int q3 = atoi(q.c_str());
                    int p = q3 - (q1 + q2);
                    if ((p < 0) || (p > 1))
                    {
                        result.push_back("NONE");
                        break;
                    }
                    if (p == 0) P0 += "0";
                    if (p == 1) P0 += "1";

                }
            }

            return result;
        }
};

int main()
{
    BinaryCode bcode;
    string s1;
    vector <string> res;
    s1 = "123";
    //s1 = "11";
    //s1 = "123210122";
    //s1 = "22111";
    //s1 = "3";
    //s1 = "123210120";
    res = bcode.decode(s1);
    for (int i =0; i < res.size(); ++i)
        cout<<i<<"result is"<<res[i]<<endl;
}

BadVocabulary.cpp - On 01 Oct,2011.

#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <cmath>
using namespace std;

class BadVocabulary {
public:
    int count(string badPrefix, string badSuffix, string badSubstring, vector <string> vocabulary) {
        int res=0,i;
    string word,reversed_test,reversed_word;
    int len= vocabulary.size();
    size_t found1,found2,found3;

    for(i = 0; i< len; i++)
    {
        word = vocabulary[i];

        found1 = word.find(badPrefix);
        found2 = word.find(badSuffix);
        found3 = word.find(badSubstring,1);

        if (found1 != string::npos || found2 != string::npos || found3 !=string::npos)
        {
            if (found1 != string::npos)
            {
                if (int(found1) == 0)
                {
                    res++;
                    continue;
                }
            }

            if (found2 != string::npos)
            {
                
                reversed_test = badSuffix;
                reversed_word = word;
                reverse(reversed_test.begin(), reversed_test.end());
                reverse(reversed_word.begin(), reversed_word.end());

                found2 = reversed_word.find(reversed_test);
                if (found2 != string::npos)
                {
                    if (int(found2) == 0)
                    {
                        res++;
                        continue;
                    }
                }
            }

            if (found3 != string::npos)
            {
                reversed_test = badSubstring;
                reversed_word = word;
                reverse(reversed_test.begin(), reversed_test.end());
                reverse(reversed_word.begin(), reversed_word.end());

                found3 = reversed_word.find(reversed_test,1);
                if (found3 != string::npos)
                {
                        res++;
                        continue;
                }

            }

        }

    }
    
        return res;
    }

};

SlimeXSlimeRancher2.cpp - On 01 Oct,2011.

#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <cmath>
using namespace std;

vector<string> split( const string& s, const string& delim =" " ) {
    vector<string> res;
    string t;
    for ( int i = 0 ; i != s.size() ; i++ ) {
        if ( delim.find( s[i] ) != string::npos ) {
            if ( !t.empty() ) {
                res.push_back( t );
                t = "";
            }
        } else {
            t += s[i];
        }
    }
    if ( !t.empty() ) {
        res.push_back(t);
    }
    return res;
}

vector<int> splitInt( const string& s, const string& delim =" " ) {
    vector<string> tok = split( s, delim );
    vector<int> res;
    for ( int i = 0 ; i != tok.size(); i++ )
        res.push_back( atoi( tok[i].c_str() ) );
    return res;
}

// BEGIN CUT HERE
#define ARRSIZE(x) (sizeof(x)/sizeof(x[0]))

template<typename T> void print( T a ) {
    cerr << a;
}
static void print( long long a ) {
    cerr << a << "L";
}
static void print( string a ) {
    cerr << '"' << a << '"';
}
template<typename T> void print( vector<T> a ) {
    cerr << "{";
    for ( int i = 0 ; i != a.size() ; i++ ) {
        if ( i != 0 ) cerr << ", ";
        print( a[i] );
    }
    cerr << "}" << endl;
}
template<typename T> void eq( int n, T have, T need ) {
    if ( have == need ) {
        cerr << "Case " << n << " passed." << endl;
    } else {
        cerr << "Case " << n << " failed: expected ";
        print( need );
        cerr << " received ";
        print( have );
        cerr << "." << endl;
    }
}
template<typename T> void eq( int n, vector<T> have, vector<T> need ) {
    if( have.size() != need.size() ) {
        cerr << "Case " << n << " failed: returned " << have.size() << " elements; expected " << need.size() << " elements.";
        print( have );
        print( need );
        return;
    }
    for( int i= 0; i < have.size(); i++ ) {
        if( have[i] != need[i] ) {
            cerr << "Case " << n << " failed. Expected and returned array differ in position " << i << ".";
            print( have );
            print( need );
            return;
        }
    }
    cerr << "Case " << n << " passed." << endl;
}
static void eq( int n, string have, string need ) {
    if ( have == need ) {
        cerr << "Case " << n << " passed." << endl;
    } else {
        cerr << "Case " << n << " failed: expected ";
        print( need );
        cerr << " received ";
        print( have );
        cerr << "." << endl;
    }
}
// END CUT HERE
class SlimeXSlimeRancher2 {
public:
    int train(vector <int> attributes) {
        int res;
    sort(attributes.begin(),attributes.end());
    int elem;
    int value;
    value = 0;
    elem = attributes.back();
    vector<int>::iterator it;
    for(it = attributes.begin();it<attributes.end();it++)
        value += abs(*it-elem);

        return value;
    }

};
// BEGIN CUT HERE
int main( int argc, char* argv[] ) {
    {
        int attributesARRAY[] = {1,2,3};
        vector <int> attributes( attributesARRAY, attributesARRAY+ARRSIZE(attributesARRAY) );
        SlimeXSlimeRancher2 theObject;
        eq(0, theObject.train(attributes),3);
    }
    {
        int attributesARRAY[] = {5,5};
        vector <int> attributes( attributesARRAY, attributesARRAY+ARRSIZE(attributesARRAY) );
        SlimeXSlimeRancher2 theObject;
        eq(1, theObject.train(attributes),0);
    }
    {
        int attributesARRAY[] = {900,500,100};
        vector <int> attributes( attributesARRAY, attributesARRAY+ARRSIZE(attributesARRAY) );
        SlimeXSlimeRancher2 theObject;
        eq(2, theObject.train(attributes),1200);
    }
}
// END CUT HERE

Graduation2.cpp - On 05 Sep,2011.

#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <cmath>

#define CLASSTAKEN 1
#define MAXSIZE 126
#define NOTVISITED -1
#define VISITED -2

using namespace std;

vector<string> split( const string& s, const string& delim =" " ) {
    vector<string> res;
    string t;
    for ( int i = 0 ; i != s.size() ; i++ ) {
        if ( delim.find( s[i] ) != string::npos ) {
            if ( !t.empty() ) {
                res.push_back( t );
                t = "";
            }
        } else {
            t += s[i];
        }
    }
    if ( !t.empty() ) {
        res.push_back(t);
    }
    return res;
}

vector<int> splitInt( const string& s, const string& delim =" " ) {
    vector<string> tok = split( s, delim );
    vector<int> res;
    for ( int i = 0 ; i != tok.size(); i++ )
        res.push_back( atoi( tok[i].c_str() ) );
    return res;
}

// BEGIN CUT HERE
#define ARRSIZE(x) (sizeof(x)/sizeof(x[0]))

template<typename T> void print( T a ) {
    cerr << a;
}
static void print( long long a ) {
    cerr << a << "L";
}

static void print( string a ) {
    cerr << '"' << a << '"';
}
template<typename T> void print( vector<T> a ) {
    cerr << "{";
    for ( int i = 0 ; i != a.size() ; i++ ) {
        if ( i != 0 ) cerr << ", ";
        print( a[i] );
    }
    cerr << "}" << endl;
}
template<typename T> void eq( int n, T have, T need ) {
    if ( have == need ) {
        cerr << "Case " << n << " passed." << endl;
    } else {
        cerr << "Case " << n << " failed: expected ";
        print( need );
        cerr << " received ";
        print( have );
        cerr << "." << endl;
    }
}
template<typename T> void eq( int n, vector<T> have, vector<T> need ) {
    if( have.size() != need.size() ) {
        cerr << "Case " << n << " failed: returned " << have.size() << " elements; expected " << need.size() << " elements.";
        print( have );
        print( need );
        return;
    }
    for( int i= 0; i < have.size(); i++ ) {
        if( have[i] != need[i] ) {
            cerr << "Case " << n << " failed. Expected and returned array differ in position " << i << ".";
            print( have );
            print( need );
            return;
        }
    }
    cerr << "Case " << n << " passed." << endl;
}
static void eq( int n, string have, string need ) {
    if ( have == need ) {
        cerr << "Case " << n << " passed." << endl;
    } else {
        cerr << "Case " << n << " failed: expected ";
        print( need );
        cerr << " received ";
        print( have );
        cerr << "." << endl;
    }
}

typedef vector<int> VI;  typedef vector<vector<int> > VVI;
typedef vector<string> VS;  typedef vector<vector<string> > VVS;
typedef signed long long i64;  typedef unsigned long long u64;

int taken[128];

// NOTE: returns -1 for unmatched items.  nm is number of matchable items.
int bipartitematch(const vector<vector<int> > &m, int nm = 128) {
  vector<int> mat(nm, -1), ret(m.size(), -1);
  int i, j, x, y;
  int retn = 0;

  for( i = 0; i < m.size(); i++ ) {
    queue<int> q;
    vector<int> pred(m.size(), -1);
    q.push(i);
    pred[i] = -2;
    while( !q.empty() ) {
      x = q.front(); q.pop();
      for( j = 0; j < m[x].size(); j++ ) if( taken[m[x][j]] ) {
    cout<<m[x][j]<<endl;
        y = mat[m[x][j]];
        if( y == -1 ) goto found;
        if( pred[y] != -1 ) continue;
        pred[y] = x;
        q.push(y);
      }
    }
    continue;
found:  y = m[x][j];
    retn++;
    while( x != -2 ) {
      mat[y] = x;
      swap(ret[x], y);
      x = pred[x];
    }
  }
  return retn;
}

class Graduation {
public:
string moreClasses(string a, vector <string> b) {
  int i, j, k, x, y, z, n;
  string ret = "";
  VVI m;

  for( i = 0; i < b.size(); i++ ) {
    n = atoi(b[i].c_str());
    for( j = 0; j < n; j++ ) {
      m.push_back(VI());
      for( k = 0; k < b[i].size(); k++ ) if( !isdigit(b[i][k]) )
        m.back().push_back(b[i][k]);
    }
  }
  if( m.size() > 128 ) return "0";
  for( i = 0; i < a.size(); i++ ) taken[a[i]] = 1;
  n = m.size()-bipartitematch(m);
  x = 33;
  while( n ) {
    if( x >= 128 ) return "0";
    if( taken[x] ) {x++; continue;}
    taken[x] = 1;
    if (x >= 67)
        cout<<x;
    z = m.size()-bipartitematch(m);
    if( z == n )
      taken[x] = 0;
    else
      ret += x;
    n = z;
    x++;
  }
  return ret;
}
}; 

int main( int argc, char* argv[] ) {
    {
        string requirementsARRAY[] = {"2ABC","2CDE"};
        vector <string> requirements( requirementsARRAY, requirementsARRAY+ARRSIZE(requirementsARRAY) );
        Graduation theObject;
        eq(0, theObject.moreClasses("A", requirements),"BCD");
    }
    {
        string requirementsARRAY[] = {"3NAMT","2+/","1M"};
        vector <string> requirements( requirementsARRAY, requirementsARRAY+ARRSIZE(requirementsARRAY) );
        Graduation theObject;
        eq(1, theObject.moreClasses("+/NAMT", requirements),"");
    }
    {
        string requirementsARRAY[] = {"100%*Klju"};
        vector <string> requirements( requirementsARRAY, requirementsARRAY+ARRSIZE(requirementsARRAY) );
        Graduation theObject;
        eq(2, theObject.moreClasses("A", requirements),"0");
    }
    {
        string requirementsARRAY[] = {"5ABCDE","1BCDE,"};
        vector <string> requirements( requirementsARRAY, requirementsARRAY+ARRSIZE(requirementsARRAY) );
        Graduation theObject;
        eq(3, theObject.moreClasses("", requirements),",ABCDE");
    }
    {
        string requirementsARRAY[] = {"2AP", "3CDEF", "1CDEFH"};
        vector <string> requirements( requirementsARRAY, requirementsARRAY+ARRSIZE(requirementsARRAY) );
        Graduation theObject;
        eq(4, theObject.moreClasses("CDH", requirements),"AEP");
    }
}
// END CUT HERE

Graduation.cpp - On 05 Sep,2011.

#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <cmath>

#define CLASSTAKEN 1
#define MAXSIZE 126
#define NOTVISITED -1
#define VISITED -2

using namespace std;

int taken[MAXSIZE];

vector<string> split( const string& s, const string& delim =" " ) {
    vector<string> res;
    string t;
    for ( int i = 0 ; i != s.size() ; i++ ) {
        if ( delim.find( s[i] ) != string::npos ) {
            if ( !t.empty() ) {
                res.push_back( t );
                t = "";
            }
        } else {
            t += s[i];
        }
    }
    if ( !t.empty() ) {
        res.push_back(t);
    }
    return res;
}

vector<int> splitInt( const string& s, const string& delim =" " ) {
    vector<string> tok = split( s, delim );
    vector<int> res;
    for ( int i = 0 ; i != tok.size(); i++ )
        res.push_back( atoi( tok[i].c_str() ) );
    return res;
}

// BEGIN CUT HERE
#define ARRSIZE(x) (sizeof(x)/sizeof(x[0]))

template<typename T> void print( T a ) {
    cerr << a;
}
static void print( long long a ) {
    cerr << a << "L";
}

static void print( string a ) {
    cerr << '"' << a << '"';
}
template<typename T> void print( vector<T> a ) {
    cerr << "{";
    for ( int i = 0 ; i != a.size() ; i++ ) {
        if ( i != 0 ) cerr << ", ";
        print( a[i] );
    }
    cerr << "}" << endl;
}
template<typename T> void eq( int n, T have, T need ) {
    if ( have == need ) {
        cerr << "Case " << n << " passed." << endl;
    } else {
        cerr << "Case " << n << " failed: expected ";
        print( need );
        cerr << " received ";
        print( have );
        cerr << "." << endl;
    }
}
template<typename T> void eq( int n, vector<T> have, vector<T> need ) {
    if( have.size() != need.size() ) {
        cerr << "Case " << n << " failed: returned " << have.size() << " elements; expected " << need.size() << " elements.";
        print( have );
        print( need );
        return;
    }
    for( int i= 0; i < have.size(); i++ ) {
        if( have[i] != need[i] ) {
            cerr << "Case " << n << " failed. Expected and returned array differ in position " << i << ".";
            print( have );
            print( need );
            return;
        }
    }
    cerr << "Case " << n << " passed." << endl;
}
static void eq( int n, string have, string need ) {
    if ( have == need ) {
        cerr << "Case " << n << " passed." << endl;
    } else {
        cerr << "Case " << n << " failed: expected ";
        print( need );
        cerr << " received ";
        print( have );
        cerr << "." << endl;
    }
}

int bipartitematch(const vector <vector <int> > &set_of_requirements)
{

    int q_item;
    int retn = 0;
    int path, classindex;
    int class_value;

    int size_of_requirements = set_of_requirements.size();

    vector <int> source(MAXSIZE, NOTVISITED);
    vector <int> target(size_of_requirements, NOTVISITED);

    for (int elem = 0; elem < size_of_requirements; elem++)
    {
        queue<int> q_of_elements;
        q_of_elements.push(elem);

        vector<int> previous(size_of_requirements, NOTVISITED);

        previous[elem] = VISITED;

        while (!q_of_elements.empty())
        {
            q_item = q_of_elements.front(); q_of_elements.pop();

            for (classindex = 0; classindex < set_of_requirements[q_item].size(); classindex++)
            {
                class_value =  set_of_requirements[q_item][classindex];

                if (taken[class_value])
                {
                    // Augumenting path logic.
                    //
                    if (source[class_value] == NOTVISITED)
                        goto found;

                    path = source[class_value];

                    if (previous[path] == NOTVISITED)
                    {
                        // This is BFS.
                        // Similar to kho-kho game.
                        previous[path] = q_item;
                        q_of_elements.push(path);
                    }
                    else 
                        continue;
                }
            }
        }
        continue;
        found:
            path = set_of_requirements[q_item][classindex];
            retn++;
            while (q_item != VISITED)
            {
                source[path] = q_item;
                swap(target[q_item], path);
                //target[q_item] = path;
                q_item = previous[q_item];
            }

    }

    return retn;
}

class Graduation {
public:
    string moreClasses(string classesTaken, vector <string> requirements) {
        vector <vector <int> > m; // [[], [], []]
        int remaining, paths;
        int nextclass;
        string res="";

        for (int ct=0; ct<classesTaken.size(); ct++)
            taken[classesTaken[ct]] = CLASSTAKEN;

        for (int i=0; i<requirements.size(); i++)
        {
            int num = atoi(requirements[i].c_str());
            for (int choice=0; choice < num; choice++)
            {
                m.push_back(vector<int>());
                for (int j=0; j < requirements[i].size(); j++)
                    if (isalpha(requirements[i][j]))
                        m.back().push_back(requirements[i][j]);
            }
        }

        if (m.size() > MAXSIZE) return "0";

        remaining = m.size() - bipartitematch(m);

        nextclass = 33;
        
        while (remaining)
        {
            if (nextclass >= MAXSIZE) return "0";

            if (taken[nextclass])
            {
                nextclass++;
                continue;
            }
            taken[nextclass] = 1;

            paths = m.size() - bipartitematch(m);

            if (paths == remaining)
                taken[nextclass] = 0;
            else
            {
                res += nextclass;
                remaining = paths;
            }
            nextclass++;
        }

        return res;
    }

};
// BEGIN CUT HERE
int main( int argc, char* argv[] ) {
    {
        string requirementsARRAY[] = {"2ABC","2CDE"};
        vector <string> requirements( requirementsARRAY, requirementsARRAY+ARRSIZE(requirementsARRAY) );
        Graduation theObject;
        eq(0, theObject.moreClasses("A", requirements),"BCD");
    }
    {
        string requirementsARRAY[] = {"3NAMT","2+/","1M"};
        vector <string> requirements( requirementsARRAY, requirementsARRAY+ARRSIZE(requirementsARRAY) );
        Graduation theObject;
        eq(1, theObject.moreClasses("+/NAMT", requirements),"");
    }
    {
        string requirementsARRAY[] = {"100%*Klju"};
        vector <string> requirements( requirementsARRAY, requirementsARRAY+ARRSIZE(requirementsARRAY) );
        Graduation theObject;
        eq(2, theObject.moreClasses("A", requirements),"0");
    }
    {
        string requirementsARRAY[] = {"5ABCDE","1BCDE,"};
        vector <string> requirements( requirementsARRAY, requirementsARRAY+ARRSIZE(requirementsARRAY) );
        Graduation theObject;
        eq(3, theObject.moreClasses("", requirements),",ABCDE");
    }
    {
        string requirementsARRAY[] = {"2AP", "3CDEF", "1CDEFH"};
        vector <string> requirements( requirementsARRAY, requirementsARRAY+ARRSIZE(requirementsARRAY) );
        Graduation theObject;
        eq(4, theObject.moreClasses("CDH", requirements),"AEP");
    }
}
// END CUT HERE

TrainingCamp.cpp - On 26 Jul,2011.

#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <cmath>
using namespace std;

vector<string> split( const string& s, const string& delim =" " ) {
    vector<string> res;
    string t;
    for ( int i = 0 ; i != s.size() ; i++ ) {
        if ( delim.find( s[i] ) != string::npos ) {
            if ( !t.empty() ) {
                res.push_back( t );
                t = "";
            }
        } else {
            t += s[i];
        }
    }
    if ( !t.empty() ) {
        res.push_back(t);
    }
    return res;
}

vector<int> splitInt( const string& s, const string& delim =" " ) {
    vector<string> tok = split( s, delim );
    vector<int> res;
    for ( int i = 0 ; i != tok.size(); i++ )
        res.push_back( atoi( tok[i].c_str() ) );
    return res;
}

#define ARRSIZE(x) (sizeof(x)/sizeof(x[0]))

template<typename T> void print( T a ) {
    cerr << a;
}
static void print( long long a ) {
    cerr << a << "L";
}
static void print( string a ) {
    cerr << '"' << a << '"';
}
template<typename T> void print( vector<T> a ) {
    cerr << "{";
    for ( int i = 0 ; i != a.size() ; i++ ) {
        if ( i != 0 ) cerr << ", ";
        print( a[i] );
    }
    cerr << "}" << endl;
}
template<typename T> void eq( int n, T have, T need ) {
    if ( have == need ) {
        cerr << "Case " << n << " passed." << endl;
    } else {
        cerr << "Case " << n << " failed: expected ";
        print( need );
        cerr << " received ";
        print( have );
        cerr << "." << endl;
    }
}
template<typename T> void eq( int n, vector<T> have, vector<T> need ) {
    if( have.size() != need.size() ) {
        cerr << "Case " << n << " failed: returned " << have.size() << " elements; expected " << need.size() << " elements.";
        print( have );
        print( need );
        return;
    }
    for( int i= 0; i < have.size(); i++ ) {
        if( have[i] != need[i] ) {
            cerr << "Case " << n << " failed. Expected and returned array differ in position " << i << ".";
            print( have );
            print( need );
            return;
        }
    }
    cerr << "Case " << n << " passed." << endl;
}
static void eq( int n, string have, string need ) {
    if ( have == need ) {
        cerr << "Case " << n << " passed." << endl;
    } else {
        cerr << "Case " << n << " failed: expected ";
        print( need );
        cerr << " received ";
        print( have );
        cerr << "." << endl;
    }
}

class TrainingCamp {
public:
    vector <string> determineSolvers(vector <string> attendance, vector <string> problemTopics) {
        vector <string> res;
    vector <string>::iterator it;
    vector <string>::iterator it2;
    string each_string; 
    string each_string2;
    int len_of_string;
    int c;
    string s;
    string s2;
    string s3;
    int pass;

    for(it = attendance.begin(); it < attendance.end(); it++)
    {
        each_string = *it;
        len_of_string = each_string.length();
        s = "";
        for(it2 = problemTopics.begin(); it2 < problemTopics.end(); it2++)
        {
            each_string2 = *it2;
            pass = 1;
            for (c= 0; c < len_of_string; c++)
            {
                if ((each_string[c] == '-' )&& (each_string2[c] == 'X'))
                {
                    pass = 0;
                    break;
                }

            }
            if (pass == 1)
                s += "X";
            else
                s += "-";
        }
        res.push_back(s);
    }
        return res;
    }

};

int main( int argc, char* argv[] ) {
    {
        string attendanceARRAY[] = {"XXX",
            "XXX",
            "XX-"};
        vector <string> attendance( attendanceARRAY, attendanceARRAY+ARRSIZE(attendanceARRAY) );
        string problemTopicsARRAY[] = {"---",
            "XXX",
            "-XX",
            "XX-"};
        vector <string> problemTopics( problemTopicsARRAY, problemTopicsARRAY+ARRSIZE(problemTopicsARRAY) );
        string retrunValueARRAY[] = {"XXXX", "XXXX", "X--X" };
        vector <string> retrunValue( retrunValueARRAY, retrunValueARRAY+ARRSIZE(retrunValueARRAY) );
        TrainingCamp theObject;
        eq(0, theObject.determineSolvers(attendance, problemTopics),retrunValue);
    }
    {
        string attendanceARRAY[] = {"-XXXX",
            "----X",
            "XXX--",
            "X-X-X"};
        vector <string> attendance( attendanceARRAY, attendanceARRAY+ARRSIZE(attendanceARRAY) );
        string problemTopicsARRAY[] = {"X---X",
            "-X---",
            "XXX--",
            "--X--"};
        vector <string> problemTopics( problemTopicsARRAY, problemTopicsARRAY+ARRSIZE(problemTopicsARRAY) );
        string retrunValueARRAY[] = {"-X-X", "----", "-XXX", "X--X" };
        vector <string> retrunValue( retrunValueARRAY, retrunValueARRAY+ARRSIZE(retrunValueARRAY) );
        TrainingCamp theObject;
        eq(1, theObject.determineSolvers(attendance, problemTopics),retrunValue);
    }
    {
        string attendanceARRAY[] = {"-----",
            "XXXXX"};
        vector <string> attendance( attendanceARRAY, attendanceARRAY+ARRSIZE(attendanceARRAY) );
        string problemTopicsARRAY[] = {"XXXXX",
            "-----",
            "--X-X"};
        vector <string> problemTopics( problemTopicsARRAY, problemTopicsARRAY+ARRSIZE(problemTopicsARRAY) );
        string retrunValueARRAY[] = {"-X-", "XXX" };
        vector <string> retrunValue( retrunValueARRAY, retrunValueARRAY+ARRSIZE(retrunValueARRAY) );
        TrainingCamp theObject;
        eq(2, theObject.determineSolvers(attendance, problemTopics),retrunValue);
    }
    {
        string attendanceARRAY[] = {"-",
            "X",
            "X",
            "-",
            "X"};
        vector <string> attendance( attendanceARRAY, attendanceARRAY+ARRSIZE(attendanceARRAY) );
        string problemTopicsARRAY[] = {"-",
            "X"};
        vector <string> problemTopics( problemTopicsARRAY, problemTopicsARRAY+ARRSIZE(problemTopicsARRAY) );
        string retrunValueARRAY[] = {"X-", "XX", "XX", "X-", "XX" };
        vector <string> retrunValue( retrunValueARRAY, retrunValueARRAY+ARRSIZE(retrunValueARRAY) );
        TrainingCamp theObject;
        eq(3, theObject.determineSolvers(attendance, problemTopics),retrunValue);
    }
    {
        string attendanceARRAY[] = {"X----X--X",
            "X--X-X---",
            "--X-X----",
            "XXXX-X-X-",
            "XXXX--XXX"};
        vector <string> attendance( attendanceARRAY, attendanceARRAY+ARRSIZE(attendanceARRAY) );
        string problemTopicsARRAY[] = {"X----X-X-",
            "-----X---",
            "-X----X-X",
            "-X-X-X---",
            "-----X---",
            "X-------X"};
        vector <string> problemTopics( problemTopicsARRAY, problemTopicsARRAY+ARRSIZE(problemTopicsARRAY) );
        string retrunValueARRAY[] = {"-X--XX", "-X--X-", "------", "XX-XX-", "--X--X" };
        vector <string> retrunValue( retrunValueARRAY, retrunValueARRAY+ARRSIZE(retrunValueARRAY) );
        TrainingCamp theObject;
        eq(4, theObject.determineSolvers(attendance, problemTopics),retrunValue);
    }
}

SlimeXSlimesCity.cpp - On 26 Jun,2011.

// BEGIN CUT HERE 
// END CUT HERE
#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <cmath>
using namespace std;

vector<string> split( const string& s, const string& delim =" " ) {
    vector<string> res;
    string t;
    for ( int i = 0 ; i != s.size() ; i++ ) {
        if ( delim.find( s[i] ) != string::npos ) {
            if ( !t.empty() ) {
                res.push_back( t );
                t = "";
            }
        } else {
            t += s[i];
        }
    }
    if ( !t.empty() ) {
        res.push_back(t);
    }
    return res;
}

vector<int> splitInt( const string& s, const string& delim =" " ) {
    vector<string> tok = split( s, delim );
    vector<int> res;
    for ( int i = 0 ; i != tok.size(); i++ )
        res.push_back( atoi( tok[i].c_str() ) );
    return res;
}

// BEGIN CUT HERE
#define ARRSIZE(x) (sizeof(x)/sizeof(x[0]))

template<typename T> void print( T a ) {
    cerr << a;
}
static void print( long long a ) {
    cerr << a << "L";
}
static void print( string a ) {
    cerr << '"' << a << '"';
}
template<typename T> void print( vector<T> a ) {
    cerr << "{";
    for ( int i = 0 ; i != a.size() ; i++ ) {
        if ( i != 0 ) cerr << ", ";
        print( a[i] );
    }
    cerr << "}" << endl;
}
template<typename T> void eq( int n, T have, T need ) {
    if ( have == need ) {
        cerr << "Case " << n << " passed." << endl;
    } else {
        cerr << "Case " << n << " failed: expected ";
        print( need );
        cerr << " received ";
        print( have );
        cerr << "." << endl;
    }
}
template<typename T> void eq( int n, vector<T> have, vector<T> need ) {
    if( have.size() != need.size() ) {
        cerr << "Case " << n << " failed: returned " << have.size() << " elements; expected " << need.size() << " elements.";
        print( have );
        print( need );
        return;
    }
    for( int i= 0; i < have.size(); i++ ) {
        if( have[i] != need[i] ) {
            cerr << "Case " << n << " failed. Expected and returned array differ in position " << i << ".";
            print( have );
            print( need );
            return;
        }
    }
    cerr << "Case " << n << " passed." << endl;
}
static void eq( int n, string have, string need ) {
    if ( have == need ) {
        cerr << "Case " << n << " passed." << endl;
    } else {
        cerr << "Case " << n << " failed: expected ";
        print( need );
        cerr << " received ";
        print( have );
        cerr << "." << endl;
    }
}
// END CUT HERE
class SlimeXSlimesCity {
public:
    int merge(vector <int> population) {
        int res;
    vector <vector <int> > cycles;
    vector <int> apopulation;
    vector<int>:: iterator it;
    int s;
    int i;
    int j;
    int k;
    int elem;
    s = population.size();
    for (i=0; i < population.size();i++)
        cycles.push_back(population);
    for (i=0; i < population.size();i++)
    {
        j = i;
        apopulation = cycles.at(i);
        for (k =0; k<j; k++)
        {
            elem = apopulation[k];
            apopulation.erase(apopulation.begin() + 1);
            apopulation.push_back(elem);
        }
        cycles[i] = apopulation;

    }
    /**
    for (it = cycles.begin(); it < cycles.end(); it++)
    {
        apopulation = *it;
    }

    **/
        return res;
    }

};
// BEGIN CUT HERE
int main( int argc, char* argv[] ) {
    {
        int populationARRAY[] = {2, 3, 4};
        vector <int> population( populationARRAY, populationARRAY+ARRSIZE(populationARRAY) );
        SlimeXSlimesCity theObject;
        eq(0, theObject.merge(population),2);
    }
    {
        int populationARRAY[] = {1, 2, 3};
        vector <int> population( populationARRAY, populationARRAY+ARRSIZE(populationARRAY) );
        SlimeXSlimesCity theObject;
        eq(1, theObject.merge(population),2);
    }
    {
        int populationARRAY[] = {8,2,3,8};
        vector <int> population( populationARRAY, populationARRAY+ARRSIZE(populationARRAY) );
        SlimeXSlimesCity theObject;
        eq(2, theObject.merge(population),2);
    }
    {
        int populationARRAY[] = {1000000000, 999999999, 999999998, 999999997};
        vector <int> population( populationARRAY, populationARRAY+ARRSIZE(populationARRAY) );
        SlimeXSlimesCity theObject;
        eq(3, theObject.merge(population),3);
    }
    {
        int populationARRAY[] = {1,1,1};
        vector <int> population( populationARRAY, populationARRAY+ARRSIZE(populationARRAY) );
        SlimeXSlimesCity theObject;
        eq(4, theObject.merge(population),3);
    }
    {
        int populationARRAY[] = {1, 2, 4, 6, 14, 16, 20};
        vector <int> population( populationARRAY, populationARRAY+ARRSIZE(populationARRAY) );
        SlimeXSlimesCity theObject;
        eq(5, theObject.merge(population),3);
    }
}
// END CUT HERE

AllButOneDivisor.cpp - On 26 Jun,2011.

#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <cmath>
#include <iostream>
#include <numeric>
using namespace std;

int gcd(int a, int b)
{
    for (;;)
    {
        if (a == 0) return b;
        b %= a;
        if (b == 0) return a;
        a %= b;
    }
}

int lcm(int a, int b)
{
    int temp = gcd(a, b);

    return temp ? (a / temp * b) : 0;
}

int lcmofvectors(vector <int> divisorsminusone)
{
    int result;
    result = accumulate(divisorsminusone.begin(),divisorsminusone.end(),1,lcm);
    return result;
}

class AllButOneDivisor {
public:
    int getMinimum(vector <int> divisors) {
        int res;
    vector <int> copyofdivisors;
    vector <int> answers;
    int i;
    int elem;
    int lcm;
    int found=-1;
    sort(divisors.begin(),divisors.end());
    reverse(divisors.begin(),divisors.end());
    for(i = 0; i<divisors.size();i++)
    {
        copyofdivisors = divisors;
        elem = divisors[i];
        copyofdivisors.erase(copyofdivisors.begin()+i);
        lcm = lcmofvectors(copyofdivisors);
        if ((lcm % elem ) == 0)
            continue;
        else
        {
            answers.push_back(lcm);
            found = 1;
        }
        /** if (found != -1)
            break;
        **/

    }
    if (found != -1)
    {
        sort(answers.begin(),answers.end());
        res = answers[0];
    }
    else
        res = -1;
    //res = found;
        return res;
    }

};

Last Updated: 16 Apr of 14

Comments by Disqus