HZAU_1209_Deadline(贪心)

来源:互联网 发布:如何摆脱抑郁症知乎 编辑:程序博客网 时间:2024/06/06 12:44

原题

 Deadline

Time Limit: 2 Sec  Memory Limit: 1280 MB

Description

     There are N bugs to be repaired and some engineers whose abilities are roughly equal. And an engineer can repair bug per day. Each bug has a deadline A[i].

      Question: How many engineers can repair all bugs before those deadlines at least?

      1<=n<= 1e6. 1<=a[i] <=1e9 

Input

       There are multiply test cases.

       In each case, the first line is an integer N , indicates the number of bugs. The next line is n integers indicates the deadlines of those bugs. 

Output

       There are one number indicates the answer to the question in a line for each case. 

Sample Input

4
1 2 3 4

Sample Output

1

题意


     程序员一天可以修复一个 bug ,现在给你n个bug 以及其修复截止日期,问最少需要多少个程序员才可以完成任务。

思路


     n 的范围是 [1,10^6] ,也就是最多有 10^6 个 bug 。

     若只有一个程序员,则修复速度为一天一个,所以所有的bug能在10^6这一天刚好修复完,所以修复截止日期在 10^6 以后的 bug 我们不予考虑,因为它总能被修复。

     △贪心算法:对于前 i 天需要修复的 bug ,我们把它在 i 天内平均分配给的人数至少是sum除以i并对其向上取整 ,例如8个bug要在前3天修复,则程序员数至少为⌈8÷3⌉=3。

for循环从i到n,找到最大的⌈sum/i⌉即为题目所求。


涉及知识及算法


1.
向上取整的运算称为Ceiling,用数学符号⌈⌉表示;

用数学算式实现:(sum-1)/i+1 函数实现:ceil(x) x为double, float类型数值

向下取整的运算称为Floor,用数学符号⌊⌋表示。

用数学算式实现:sum/i 函数实现:floor(x) x为double, float类型数值

2.贪心算法(又称贪婪算法)是指,在对问题求解时,总是做出在当前看来是最好的选择。也就是说,不从整体最优上加以考虑,他所做出的是在某种意义上的局部最优解。
——摘自百度百科

在本题中,要求整体需要的最优(少)程序员数,就先求当前最优(少)程序员数。在每个状态下的最优(少)程序员数中的最大者即为整体所要求的最优(少)程序员数。

代码实现


#include <stdio.h>#include <string.h>#include <iostream>#include <algorithm>using namespace std; int a[1000009];          //记录各个截止日期有多少天const int maxn = 1e6;int main(){    int n,b;              //b存放截止日期    while(~scanf("%d",&n))    {        memset(a,0,sizeof(a));       //将a数组清零 头文件<string.h>        for(int i=1; i<=n; i++)        {            scanf("%d",&b);            if(b<=maxn)a[b]++;        //例:如果截止日期为6,则a[6]加一。        }        int sum=0,ans=1;             //sum记录前i天的bug总数        for(int i=1; i<=maxn; i++)        {            sum+=a[i];            int t=((sum-1)/i+1);       //t为前i天至少需要的程序员数            ans=max(ans,t);             //max函数目的是在各个“最少程序员数”中取得最大的值 头文件 <algorithm>        }        printf("%d\n",ans);    }    return 0;} /**************************************************************    Problem: 1209    Language: C++    Result: Accepted    Time:1211 ms    Memory:5404 kb****************************************************************/

代码及部分内容引用自博主小坏蛋_千千,附上他的文章网址点击打开链接,向他表示感谢。

原创粉丝点击