您的位置:首页 > 其它

codeforces 792C —— Divide by Three(分类讨论)

2017-03-29 22:30 274 查看
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, 0, 99, 10110 are
beautiful numbers, and 00, 03, 122 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.

感觉可以用dp做啊,我直接分类讨论了。

因为每一个数模三只能是1或者2,如果一个数想要被三整除,也就是各个位置上的数加起来能整除三,那么最多只需要抹去两个数就行了。

为什么呢?比如我现在加起来模三为1,那么只要抹去一个模三为1的或者两个模三为2的,所以讨论一下即可。

#include <cstdio>
#include <cstring>
#include <queue>
#include <algorithm>
using namespace std;

const int MAXN = 200000+10;
char a[MAXN];
int vis[MAXN];
void pri(int n){
for(int i=0;i<n;i++){
if(!vis[i])
printf("%c",a[i]);
}
printf("\n");
}
int b[MAXN];
int main(){
scanf("%s",a);
int s=0,n=(int)strlen(a);
for(int i=0;i<n;i++){
b[i]=a[i]-'0';
s+=b[i];
b[i]=b[i]%3;

}
if(s%3==0){
pri(n);
return 0;
}
int x=s%3;
int y=3-x;
int ok=0;
for(int i=n-1;i>=0;i--){
if(b[i]==x){
if(i!=0||(a[1]!='0'&&n>1)){
vis[i]=1;
pri(n);
return 0;
}
for(ok=1;ok<=n-1;ok++){
if(a[ok]!='0'){
ok--;
break;
}
}
if(ok==n){
ok--;
if(n==1){
puts("-1");
return 0;
}
}
}
}
int r1=0,r2=0;
for(int i=n-1;i>=0;i--){
if(b[i]==y){
if(r1){
r2=i;
break;
}else{
r1=i;
}
}
}
if(r1==0){
if(ok){
vis[0]=1;
if(ok==n-1){
puts("0");
return 0;
}
for(int i=0;i<ok;i++){
vis[i+1]=1;
}
pri(n);
return 0;
}else{
puts("0");
return 0;
}
}
if(r2!=0){
vis[r1]=1;
vis[r2]=1;
pri(n);
return 0;
}else{
if(n==2){
puts("-1");
return 0;
}
vis[r2]=1;
vis[r1]=1;
int i;
for(i=1;i<n;i++){
if(a[i]!='0'&&i!=r1){
break;
}
else{
vis[i]=1;
}
}
if(i==n){
puts("0");
}else{
pri(n);
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: