0和5 (51Nod)

小K手中有n张牌,每张牌上有一个一位数的数,这个字数不是0就是5。小K从这些牌在抽出任意张(不能抽0张),排成一行这样就组成了一个数。使得这个数尽可能大,而且可以被90整除。

注意:

1.这个数没有前导0,

2.小K不需要使用所有的牌。

Input

每个测试数据输入共2行。 
第一行给出一个n,表示n张牌。(1<=n<=1000) 
第二行给出n个整数a00,a11,a22,…,an−1n−1 (aii是0或5 ) 表示牌上的数字。

Output

共一行,表示由所给牌组成的可以被90整除的最大的数,如果没有答案则输出”-1”(没有引号)

Sample Input

4
5 0 5 0

Sample Output

0

题解:由0和5一起构成能够被90整除的第一个数是5555555550,所以只要手中牌的数为5的个数是9的倍数,且至少有一个0就可以了。

#include <cstdio>
#include <cmath>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <map>
using namespace std;
typedef long long ll;
int a[1005];
int main()
{
    int n, x, y;
    while(~scanf("%d",&n))
    {
        x = 0;
        y = 0;
        for(int i = 0; i < n; i ++)
        {
            scanf("%d",&a[i]);
            if(a[i] == 0) x ++;
            if(a[i] == 5) y ++;
        }
        if(y < 9)
        {
            if(x > 0) printf("0
");
            else printf("-1
");
        }
        else
        {
            if(x > 0)
            {
                int xx = y / 9;
                for(int i = 0; i < xx; i ++)printf("555555555");
                for(int i = 0; i < x; i ++)printf("0");
                printf("
");
            }
            else printf("-1
");
        }
    }
    return 0;
}
原文地址:https://www.cnblogs.com/lcchy/p/10139584.html