GYM 101755 C.Third-Party Software(贪心)

本文介绍了一种通过贪心算法解决函数覆盖问题的方法。给定一系列版本区间,目标是最少购买哪些版本能覆盖所有必需的游戏函数。通过将区间按右端点排序并选择合适的版本,确保了覆盖的同时达到最少购买的要求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Description

玩一个游戏需要nn个函数,第i个函数只在版本[ai,bi][ai,bi]中出现,问至少要买多少个版本才能有这nn个函数

Input

第一行一整数n表示函数个数,之后nn行每行两个整数ai,bi表示第ii个函数出现的版本区间

(1n2105,1aibi109)

Output

输出至少要买的版本数量和这些版本的编号

Sample Input

5
2 4
1 3
2 3
3 6
4 5

Sample Output

2
3 4

Solution

贪心,把所有区间按右端点升序排,右端点相同则按左端点升序排,每次买第一个区间的右端点即可,这样后面的区间只要左端点不超过该右端点就都不用买

Code

#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<vector>
#include<queue>
#include<map>
#include<set>
#include<ctime>
using namespace std;
typedef long long ll;
typedef pair<int,int>P;
const int INF=0x3f3f3f3f,maxn=200005;
int n,ans[maxn],res;
struct node
{
    int id,l,r;
    bool operator<(const node &b)const
    {
        if(r!=b.r)return r<b.r;
        return l<b.l;
    }
}a[maxn];
int main()
{
    while(~scanf("%d",&n))
    {
        for(int i=0;i<n;i++)scanf("%d%d",&a[i].l,&a[i].r),a[i].id=i+1;
        sort(a,a+n);
        res=0;
        ans[res++]=a[0].r;
        for(int i=1;i<n;i++)
            if(a[i].l<=ans[res-1])continue;
            else ans[res++]=a[i].r;
        printf("%d\n",res);
        for(int i=0;i<res;i++)printf("%d%c",ans[i],i==res-1?'\n':' ');
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值