codeforces 792C Divide by Three

C. Divide by Three
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

A positive integer number n is written on a blackboard. It consists of not more than 105 digits. You have to transform it into a beautifulnumber by erasing some of the digits, and you want to erase as few digits as possible.

The number is called beautiful if it consists of at least one digit, doesn't have leading zeroes and is a multiple of 3. For example, 099,10110 are beautiful numbers, and 0003122 are not.

Write a program which for the given n will find a beautiful number such that n can be transformed into this number by erasing as few digits as possible. You can erase an arbitraty set of digits. For example, they don't have to go one after another in the number n.

If it's impossible to obtain a beautiful number, print -1. If there are multiple answers, print any of them.

Input

The first line of input contains n — a positive integer number without leading zeroes (1 ≤ n < 10100000).

Output

Print one number — any beautiful number obtained by erasing as few as possible digits. If there is no answer, print  - 1.

Examples
input
1033
output
33
input
10
output
0
input
11
output
-1
Note

In the first example it is enough to erase only the first digit to obtain a multiple of 3. But if we erase the first digit, then we obtain a number with a leading zero. So the minimum number of digits to be erased is two.



代码:
#include <iostream>
#include <string>
using namespace std;
string k, r, t;
int c(string k)
{
    int a = 0;
    for (int i = 0; i < k.length(); ++i)a = (a + k[i] - '0') % 3;
    return a | !k.length();
}
void b(string &t)
{
    while (t[0] == '0' && t.length() > 1)t.erase(0, 1);
}
int main()
{
    cin >> k;
    int a = c(k), y = 3 - a, q = 1, w = 2;
    r = t = k;
    for (int i = k.length() - 1; i >= 0; --i)
    {
        if ((k[i] - '0') % 3 == a && q)r.erase(i, 1), q = 0;
        if ((k[i] - '0') % 3 == y && w)t.erase(i, 1), --w;
    }
    q = c(t), w = c(r), b(t), b(r);
    if (q && w)r = "-1";
    else if (t.length() > r.length() && !q || w)r = t;
    cout << r;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值