1. 程式人生 > >Codeforces 401C Team 貪心法

Codeforces 401C Team 貪心法

本題使用貪心法,關鍵是考貪心策略,同時要求要細心,我提交的時候也WA了幾次,大意題目就是如何按照給定的規則排列一個01字串,引用原題如下:

C. Team

time limit per test1 second
memory limit per test256 megabytes
inputstandard input
outputstandard output
Now it’s time of Olympiads. Vanya and Egor decided to make his own team to take part in a programming Olympiad. They’ve been best friends ever since primary school and hopefully, that can somehow help them in teamwork.

For each team Olympiad, Vanya takes his play cards with numbers. He takes only the cards containing numbers 1 and 0. The boys are very superstitious. They think that they can do well at the Olympiad if they begin with laying all the cards in a row so that:

there wouldn’t be a pair of any side-adjacent cards with zeroes in a row;
there wouldn’t be a group of three consecutive cards containing numbers one.
Today Vanya brought n cards with zeroes and m cards with numbers one. The number of cards was so much that the friends do not know how to put all those cards in the described way. Help them find the required arrangement of the cards or else tell the guys that it is impossible to arrange cards in such a way.

Input
The first line contains two integers: n (1 ≤ n ≤ 106) — the number of cards containing number 0; m (1 ≤ m ≤ 106) — the number of cards containing number 1.

Output
In a single line print the required sequence of zeroes and ones without any spaces. If such sequence is impossible to obtain, print -1.

Sample test(s)
input
1 2
output
101
input
4 8
output
110110110101
input
4 10
output
11011011011011
input
1 5
output
-1

有幾個坑,程式碼註釋的地方;判斷條件和貪心策略可以根據題意多舉例,然後總結出來:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <string>
using std::string;

int main()
{
    int zero, one;
    scanf("%d %d", &zero, &one);
    if (zero > one + 1 ||one > (zero << 1) + 2)///判斷無解條件
    {
        printf("-1\n");
    }
    else
    {
        string str;
        while (zero || one)
        {
            if (one + 1 == zero)
            {
                str.insert(str.end(), '0');
                zero--;
            }
            else if ((zero << 1) + 1 <= one)///不要寫成(zero<<1)+2 == one
            {
                if (one > 1)/// need to judge first, insure we have enough one
                {
                    str += "11";
                    one -= 2;
                }
                else
                {
                    str += "1";
                    one--;
                }
            }
            else if (str.empty() || (str.back() == '1' && zero > 0))
            {
                str.insert(str.end(), '0');
                zero--;
            }
            else
            {
                str.insert(str.end(), '1');
                one--;
            }
        }
        printf("%s\n", str.c_str());
    }

    return 0;
}