• DAY7L2【C001】


    出自附中练习场【难度C】—————————————————————————————————————————————————————————————

    【试题描述】有 N 个任务, 每个任务最多只能完成一次。另外,每个任务都有两个属性 c[i]、 d[i]。 c[i]的意思是第 i 个任务必须要在第 c[i]个单位时间或之前完成。完成第 i 个任务所需要的时间为 d[i]。 初始时 0 时刻。 求最多能完成几个任务。

    【输入】第一行: N
               接下来 N 行, d[i], c[i]

    【输出】最多能完成的任务。

    【输入样例】

    4
    100 200
    200 1300
    1000 1250
    2000 3200

    【输出样例】

    3

    【解题思路】典型贪心算法,我们称完成时间为t1,我们现在对t1进行排序,得到(样例:100 200 1000 2000)现在,我们可以建一个heap了(类似于队列),对于每一项任务,分两种大操作:插入或不插入,不插入又分两种,不做某项任务或把其他任务删除,更新为现在的任务。那么有几种触发条件1、如果当前大于等于最大,不插入2、如果小于,那就更新或插入。

    【代码在地下200m】

    ——————————————————————————————————100m————————————————————————————————-———

    ——————————————————————————————————200m————————————————————————————————————

    #include <iostream>
    #include <cstring>
    #include <queue>
    #include <cstdio>
    #include <algorithm>
    
    using namespace std;
    
    const int N=150005;
    
    struct Heap 
    {
        int A[N<<1|1], tot;
    
        void init(int n) 
    	{
            for(int i=1; i<=(n<<1|1); i++) A[i]=0;
            tot=0;
        }
    
        void Insert(int val) 
    	{
            A[++tot]=val;
            for(int x=tot; x>1 && A[x]>A[x>>1]; x>>=1) swap(A[x], A[x>>1]);
        }
    
        void Update(int val) 
    	{
            A[1]=val;
            for(int i=1, j=2; j<=tot; i=j, j<<=1) 
    		{
                if((j|1)<=tot && A[j]<A[j|1]) j|=1;
                if(A[j]<A[i]) break;
                swap(A[i], A[j]);
            }
        }
    } heap;
    
    struct data 
    {
        int t1, t2;
        bool operator < (const data &T) const 
    	{
            return t2<T.t2;
        }
    } A[N];
    int n, ans, cur;
    
    int main() 
    {
        while(scanf("%d", &n)!=EOF) 
    	{
            for(int i=0; i<n; i++) scanf("%d%d", &A[i].t1, &A[i].t2);
            sort(A, A+n);
            cur=ans=0, heap.init(n);
            for(int i=0; i<n; i++) 
    		{
                if(A[i].t1+cur<=A[i].t2) ans++, heap.Insert(A[i].t1), cur+=A[i].t1;
                else 
    			{
                    if(!heap.tot) continue;
                    int val=heap.A[1];
                    if(val<=A[i].t1) continue;
                    cur-=val-A[i].t1;
                    heap.Update(A[i].t1);
                }
            }
            printf("%d
    ", ans);
        }
        //sysytem("pause");
    	return 0;
    }
    

      

  • 相关阅读:
    config Doku wiki
    [转载]【python】ipython与python的区别
    数组和指针
    C++初始化数据成员
    RSA算法原理
    C++四种cast
    百度笔试准备2
    百度笔试准备1
    百度面试准备
    C++的空类中默认产生哪些类成员函数
  • 原文地址:https://www.cnblogs.com/lijiaxin-blog-cpp/p/4720836.html
Copyright © 2020-2023  润新知