Description
Furik loves math lessons very much, so he doesn't attend them, unlike Rubik. But now Furik wants to get a good mark for math. For that Ms. Ivanova, his math teacher, gave him a new task. Furik solved the task immediately. Can you?
You are given a set of digits, your task is to find the maximum integer that you can make from these digits. The made number must be divisible by 2, 3, 5 without a residue. It is permitted to use not all digits from the set, it is forbidden to use leading zeroes.
Each digit is allowed to occur in the number the same number of times it occurs in the set.
Input
A single line contains a single integer n (1 ≤ n ≤ 100000) — the number of digits in the set. The second line contains n digits, the digits are separated by a single space.
Output
On a single line print the answer to the problem. If such number does not exist, then you should print -1.
Sample Input
1 0
0
11 3 4 5 4 5 3 5 3 4 4 0
5554443330
8 3 2 5 1 5 2 2 3
-1
//注意前导0.
//此题思路还是很简单的,要同时被2 3 5整除。必须是整十的数而且位数和能被3整除。
//如果不能整除时,看其余数。若为1看1 4 7 位可有得减,没有的话就非零的位数找个最小的剪掉
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
using namespace std;
int A[18];
int main()
{
int n;
while(scanf("%d",&n)!=EOF)
{
bool flag=false;
memset(A,0,sizeof(A));
int a,sum=0;
for(int i=1;i<=n;i++)
{
scanf("%d",&a);
sum+=a;
A[a]++;
}
L:
if(!A[0])
{
cout<<-1<<endl;
continue;
}
else
{
if(sum%3==0)
{
flag=true;
bool ok=false;
for(int i=1;i<=9;i++)
{
if(A[i])
{
ok=true;
break;
}
}
if(ok)
{
for(int i=9;i>=0;i--)
{
while(A[i])
{
cout<<i;
A[i]--;
}
}
}
else cout<<0;
cout<<endl;
}
else if(sum%3==2)
{
if(A[2])
{
A[2]--;
sum-=2;
goto L;
}
else if(A[5])
{
A[5]--;
sum-=5;
goto L;
}
else if(A[8])
{
A[8]--;
sum-=8;
goto L;
}
else //删掉非0的最小的
{
for(int i=1;i<=9;i++)
{
if(i%3==0) continue;
if(A[i])
{
A[i]--;
sum-=i;
goto L;
}
}
}
}
else if(sum%3==1)//即(sum%3==1)
{
if(A[1])
{
A[1]--;
sum-=1;
goto L;
}
else if(A[4])
{
A[4]--;
sum-=4;
goto L;
}
else if(A[7])
{
A[7]--;
sum-=7;
goto L;
}
else //删掉非0的最小的
{
for(int i=1;i<=9;i++)
{
if(i%3==0) continue;
if(A[i])
{
A[i]--;
sum-=i;
goto L;
}
}
}
}
}
if(!flag)
{
cout<<-1<<endl;
}
}
return 0;
}