您的位置:首页 > 其它

codeforces 214B - Hometask

2013-12-30 23:58 246 查看
B. Hometask

time limit per test
2 seconds

memory limit per test
256 megabytes

input
standard input

output
standard output

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 test(s)

input
1
0


output
0


input
11
3 4 5 4 5 3 5 3 4 4 0


output
5554443330


input
8
3 2 5 1 5 2 2 3


output
-1


Note
In the first sample there is only one number you can make — 0. In the second sample the sought number is 5554443330. In the third sample it is impossible to make the required number.
 

解析:因为要求是同时2和5的倍数,所以一定要以0结尾,所以没有0就一定会输出-1。然后就是要求是3的倍数,如果sum%3==0,则全部输出,若不是,由于sum%3=1或2,不是删掉一个数就是两个数,删除一个数的情况较简单,若是需要删除两个数,就是(1+1=2)和(2+2)%3=1的情况了。注意当sum=0时,只输出一个0。

 

代码:

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

int main()
{
int n,d[10];
while(scanf("%d",&n)!=EOF)
{
int i,j,sum=0,a;
memset(d,0,sizeof(d));
for(i=0; i<n; i++)
{
scanf("%d",&a);
sum+=a;
d[a]++;
}
if(d[0]==0) printf("-1\n");
else
{
int flag=0;
if(sum%3==1)
{
if(d[1]+d[4]+d[7])
{
for(i=1; i<=7; i+=3)
if(d[i])   {d[i]--,sum-=i;break;}
}
else if(d[2]+d[5]+d[8]>=2)
for(j=1,i=2; i<=8; i+=3)
while(d[i]&&j<=2) d[i]--,sum-=i,j++;
else flag=1;
}
if(sum%3==2)
{
if(d[2]+d[5]+d[8])
{
for(i=2; i<=8; i+=3)
if(d[i])   {d[i]--,sum-=i;break;}
}
else if(d[1]+d[4]+d[7]>=2)
for(j=1,i=1; i<=7; i+=3)
while(d[i]&&j<=2) d[i]--,sum-=i,j++;
else flag=1;
}

if(!flag)
{
if(d[1]+d[2]+d[3]+d[4]+d[5]+d[6]+d[7]+d[8]+d[9])
{
for(i=9; i>=0; i--)
while(d[i]--) printf("%d",i);
printf("\n");
}
else printf("0\n");
}
else printf("0\n");
}

}

return 0;
}


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