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 感觉比较好的数学题,思路想到了,但没实现出来。。。#include<iostream> #include<string> #include<stdio.h> #include<cmath> #include<vector> #include<algorithm> using namespace std; int N,n[100010],sum = 0; void deal(int a,int b,int c,int d,int e,int f) { int temp = 0; for(int i = N - 1; i >= 0; i --) { if(n[i] == a || n[i] == b || n[i] == c) { n[i] = -1; temp = 1; break; } } if(temp == 0) { int temp1 = 0; for(int i = N - 1; i >= 0; i --) { if(temp1 == 1) break; if(n[i] == d || n[i] == e || n[i] == f) { for(int j = i - 1; j >= 0; j --) { if(temp1 == 1) break; if(n[j] == d || n[j] == e || n[j] == f) { n[j] = -1; n[i] = -1; temp1 = 1; } } } } } } void print() { int sum1 = 0; for(int i = 0; i < N; i ++) if(n[i] != -1) sum1 = sum1 + n[i]; if(sum1 % 3 == 0 && sum1 != 0) { for(int j = 0; j < N; j ++) if(n[j] != -1) cout<<n[j]; cout<<endl; } else { if(sum1 == 0) cout<<"0"<<endl; } } int main() { cin>>N; for(int i = 0; i < N; i ++) { scanf("%d",&n[i]); } sort(n,n + N,less<int>); if(N == 1 && n[0] == 0) { cout<<"0"<<endl; } else { if(n[N - 1] != 0) cout<<"-1"<<endl; else { for(int j = 0; j < N; j ++) sum = sum + n[j]; if(sum % 3 == 0) { if(n[0] == 0) { cout<<"0"<<endl; } else { for(int i = 0; i < N; i ++) cout<<n[i]; cout<<endl; } } if(sum % 3 == 1) { deal(1,4,7,2,5,8); print(); } if(sum % 3 == 2) { deal(2,5,8,1,4,7); print(); } } } return 0; }