HDU 5055 Bob and math problem(贪心)——BestCoder Round #11(div.2)

Bob and math problem

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)


Problem Description
Recently, Bob has been thinking about a math problem.
There are N Digits, each digit is between 0 and 9. You need to use this N Digits to constitute an Integer.
This Integer needs to satisfy the following conditions:
  • 1. must be an odd Integer.
  • 2. there is no leading zero.
  • 3. find the biggest one which is satisfied 1, 2.

Example: 
There are three Digits: 0, 1, 3. It can constitute six number of Integers. Only "301", "103" is legal, while "130", "310", "013", "031" is illegal. The biggest one of odd Integer is "301".
 

Input
There are multiple test cases. Please process till EOF.
Each case starts with a line containing an integer N ( 1 <= N <= 100 ).
The second line contains N Digits which indicate the digit  a1,a2,a3,,an.(0ai9) .
 

Output
The output of each test case of a line. If you can constitute an Integer which is satisfied above conditions, please output the biggest one. Otherwise, output "-1" instead.
 

Sample Input
   
   
   
   
3 0 1 3 3 5 4 2 3 2 4 6
 

Sample Output
   
   
   
   
301 425 -1
 

Source
BestCoder Round #11 (Div. 2)
 
/****************************************************/

出题人的解题思路:

 题目要求将N个数字(每个数字都是0...9)组合成一个整数。 满足以下三个条件: [1] 这个整数是一个奇数; [2] 且没有前导0; [3] 找出最大的那个满足[1][2]条件的奇数。 解法: 贪心策略。 1、先对这N个数字从大到小排序,得到的序列是一个最大的整数(但它可能还不是奇数)。 2、然后找到最小的一个奇数数字,放到最后一位,即可得到我们所求的最大奇数了。如:"98764" --> "98647"。 3、请注意前导零的情况。如:"900" --> "009" 就非法了,应该输出-1。

题意:给你n个数字a1,a2,…,an(0≤ai≤9),组成n位数,要求组成的数①是一个奇数;②没有前导0,在满足这两个前提条件下使该数尽可能大,若不存在则输出-1

解题思路:为了保证该数是一个奇数,且值尽可能大,那么我们应该挑出最小的一个奇数数字作为该数的最低位,其余的则是高位越大越好。而不存在的情况无非就三种

①n个数字均为偶数,这样我们就没有办法保证组成的数为奇数,毕竟,奇数的特征是个位数字必须是奇数

②n个数字全为0,其实这一点已经包含在①中了,刚开始分得比较细,所以这两点也分开来算

③存在0的情况下,n-1个数字为0,这样导致除了末尾非0外,前面的n-1位均为前导0,这是不符合题意的,如003。

而之所以强调是存在0的情况下,是因为,当n=1时,它满足n-1个数字为0,但不一定不存在,如5

在这就不罗嗦了,具体的看代码,有问题的尽管问,过了这个村没这个店

#pragma comment(linker, "/STACK:1024000000,1024000000")
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<queue>
#include<stack>
#include<math.h>
#include<vector>
#include<map>
#include<set>
#include<stdlib.h>
#include<cmath>
#include<string>
#include<algorithm>
#include<iostream>
#define exp 1e-10
using namespace std;
const int N = 10;
const int inf = 2147483647;
const int mod = 2009;
int s[N];
int main()
{
    int n,i,x,m;
    while(~scanf("%d",&n))
    {
        memset(s,0,sizeof(s));
        m=10;
        for(i=0;i<n;i++)
        {
            scanf("%d",&x);
            s[x]++;
            if(x%2&&x<m)
                m=x;
        }
        if(m==10||s[0]==n-1&&s[0]!=0)
        {
            puts("-1");
            continue;
        }
        s[m]--;
        for(i=9;i>=0;i--)
            while(s[i]--)
                printf("%d",i);
        printf("%d\n",m);
    }
    return 0;
}
菜鸟成长记


你可能感兴趣的:(ACM,贪心)