UVA-1617-Laptop C++版本题解

文章目录


题目链接

题解

先按照 d e a d l i n e deadline deadline 排序,然后贪心即可,可抽象为事件都紧凑在 e n d end end 附近。

  • 当当前任务的起始时间大于 e n d end end,时,更新 e n d end end为当前的 d e a d l i n e deadline deadline, 且 a n s ans ans 加一;
  • 否则 e n d end end 的更新规则是:
    • 当当前的 d e a d l i n e deadline deadline 大于 e n d end end e n d end end才加1;
    • 否则直接将任务添加到 e n d end end 之前,无需担心溢出,因为起始时间在排序时也是升序,一定放得下。

代码

/*
 * @Date: 2021-12-09 15:53:49
 * @LastEditors: fuchaoxin
 * @LastEditTime: 2021-12-09 17:19:58
 * @FilePath: \Visual Studio\UVA\Laptop.cpp
 */

#include <bits/stdc++.h>
#include <algorithm>
#include <cmath>
using namespace std;

int compare(const void *a, const void *b)
{
    int *m = (int *)a, *n = (int *)b;
    if (m[1] != n[1])
    {
        return m[1] - n[1]; // ascent
    }
    else
    {
        return m[0] - n[0]; // ascent
    }
}

int main(void)
{
    int T;
    scanf("%d", &T);
    while (T-- > 0)
    {
        int n;
        scanf("%d", &n);
        int intervals[n][2];

        // initialize the intervals
        for (int i = 0; i < n; i++)
        {
            scanf("%d%d", &intervals[i][0], &intervals[i][1]);
        }

        qsort(intervals, n, sizeof(intervals) / n, compare);

        // // display
        // for (int i = 0; i < n; i++)
        // {
        //     printf("[%d, %d]\n", intervals[i][0], intervals[i][1]);
        // }

        int end = intervals[0][1];
        int ans = 0; // num of the idle periods

        // solve
        for (int i = 1; i < n; i++)
        {
            if (intervals[i][0] > end) // the start time is bigger than current end time
            {
                end = intervals[i][1];
                ans++; // idle++
            }
            else // update the end time
            {
                if(intervals[i][1] > end){ // add after the endtime, the end time only plus one
                    end++;
                }
                // else if(intervals[i][1] == end) { // just add infront of the endtime, do worry about overflow
                //     continue;
                // } 
            }
        }

        cout << ans << endl;
    }

    return 0;
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值