题目要求将N个数字(每个数字都是0...9)组合成一个整数。
满足以下三个条件:
[1] 这个整数是一个奇数;
[2] 且没有前导0;
[3] 找出最大的那个满足[1][2]条件的奇数。
解法:
贪心策略。
1、先对这N个数字从大到小排序,得到的序列是一个最大的整数(但它可能还不是奇数)。
2、然后找到最小的一个奇数数字,放到最后一位,即可得到我们所求的最大奇数了。如:"98764" --> "98647"。
3、请注意前导零的情况。如:"900" --> "009" 就非法了,应该输出-1。
#include <iostream>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <bitset>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <climits>
#include <cstdlib>
#include <cmath>
#include <time.h>
#define maxn 1005
#define maxm 40005
#define eps 1e-10
#define mod 10000007
#define INF 1e9
#define lowbit(x) (x&(-x))
#define mp make_pair
#define ls o<<1
#define rs o<<1 | 1
#define lson o<<1, L, mid
#define rson o<<1 | 1, mid+1, R
typedef long long LL;
typedef unsigned long long ULL;
//typedef int LL;
using namespace std;
LL qpow(LL a, LL b){LL res=1,base=a;while(b){if(b%2)res=res*base;base=base*base;b/=2;}return res;}
LL powmod(LL a, LL b){LL res=1,base=a;while(b){if(b%2)res=res*base%mod;base=base*base%mod;b/=2;}return res;}
void scanf(int &__x){__x=0;char __ch=getchar();while(__ch==' '||__ch=='\n')__ch=getchar();while(__ch>='0'&&__ch<='9')__x=__x*10+__ch-'0',__ch = getchar();}
LL gcd(LL _a, LL _b){if(!_b) return _a;else return gcd(_b, _a%_b);}
//head
int c[20];
char s[maxn];
int n;
void read(void)
{
int x;
memset(c, 0, sizeof c);
for(int i = 1; i <= n; i++) scanf("%d", &x), c[x]++;
}
void work(void)
{
int len = 0, t = -1;
for(int i = 0; i < 10; i++) if(i % 2 == 1 && c[i]) {
t = i;
break;
}
if(t == -1 || (c[0] && c[0] == n-1)) {
printf("-1\n");
return;
}
s[len++] = t + '0', c[t]--;
for(int i = 0; i < 10; i++)
while(c[i]--) s[len++] = i + '0';
s[len] = 0;
for(int i = len-1; i >= 0; i--) printf("%c", s[i]);
printf("\n");
}
int main(void)
{
while(scanf("%d", &n)!=EOF) {
read();
work();
}
return 0;
}