Hatena::Grouptopcoder

TopCoderの問題を解く

解いた問題の一覧表

2009-08-29

Rochambo

| 17:09

問題文, SRM 163

じゃんけんの勝数。

157.83/250

class Rochambo {
public:
    int wins(string opponent) {
        int counter = 0;
        for (int i = 0; i < 2 && i < opponent.size(); i++)
            if (isWin('R', opponent[i]))
                counter++;
        for (int i = 2; i < opponent.size(); i++) {
            string pre2 = opponent.substr(i-2, 2);
            char move;
            if (pre2 == "RR") move = 'P';
            else if (pre2 == "SS") move = 'R';
            else if (pre2 == "PP") move = 'S';
            else if (pre2.find("R") == string::npos) move = 'P';
            else if (pre2.find("S") == string::npos) move = 'R';
            else move = 'S';
            if (isWin(move, opponent[i]))
                counter++;
        }
        return counter;
    }
private:
    bool isWin(const char a, const char b) {
        return (a=='R'&&b=='S') || (a=='S'&&b=='P') || (a=='P'&&b=='R');
    }
};

2009-08-05

Pool

| 13:05

問題文

特定のボールの積み方にするには何回ボールを交換すればいいのかを求める。

class Pool {
    public:
        int rackMoves(vector <int> triangle) {
            const static int NUM_BALLS = 15;
            const static string PATTERN = "XOOX8XOXOXXOXOO";
            int ans = 0;
            if (triangle[4] != 8) {
                swap(triangle[4], *find(triangle.begin(),triangle.end(),8));
                ans++;
            }
            int a=0, b=0;
            for (int i = 0; i < NUM_BALLS; i++) {
                if (triangle[i] <= 7) {
                    if (PATTERN[i] == 'X') a++;
                    else                   b++;
                }
            }
            ans += min(a, b);
            return ans;
        }
};

CalendarRecycle

| 19:09

問題文

次にカレンダーを使いまわせる年を求める。

class CalendarRecycle {
    public:
        int useAgain(int year) {
            int day = 0;
            const pair<bool,int> yearPair = make_pair(isLeapYear(year),day);
            for (int y = year+1; ; y++) {
                if (isLeapYear(y-1)) day = (day+366) % 7;
                else day = (day+365) % 7;
                if (yearPair == make_pair(isLeapYear(y),day))
                    return y;
            }
            return -1;
        }
    private:
        bool isLeapYear(const int year) {
            return (year%4 == 0 && year%100 != 0) || year%400 == 0;
        }
};

Inchworm

| 18:52

問題文

虫が食べた葉っぱの枚数を数える。

class Inchworm {
    public:
        int lunchtime(int branch, int rest, int leaf) {
            int consumed = 0;
            for (int p = 0; p <= branch; p += leaf) {
                if (p%rest == 0) 
                    consumed++;
            }
            return consumed;
        }
};