P1803 凌乱的yyy / 线段覆盖(贪心)

本文介绍了如何使用C++编程解决区间覆盖问题,通过先对区间按结束点排序,然后遍历计算满足条件的区间数量,实现高效的AC解决方案。
摘要由CSDN通过智能技术生成

思路:

这道题让求区间覆盖,它要求只能一个一个的区间,先对n个区间进行排序,按照区间的结束点前后进行排序。所以从后往前看结束时间点,如果下一个的起点在前一个的结束点之后,则数量加1。

0402重做!AC!

#include<algorithm>
#include<iostream>
#include<cstring>
#include<queue>
#include<cmath>
#define x first
#define y second
using namespace std;

int n;
struct node{
	int x,y;//记录开始结束结点 
};
node a[1000010];

bool cmp(node a, node b){
	return a.y < b.y;//按照结束结点从小到大 
}
int cnt=1;//记录答案
 
int main()
{
	scanf("%d",&n);
	for(int i=0;i<n;i++){
		scanf("%d%d",&a[i].x,&a[i].y);
	}
	
	sort(a,a+n,cmp);
	
	int temp = a[0].y;
	
	for(int i=1;i<n;i++){
		if(a[i].x >= temp){
			cnt++;
			temp = a[i].y;
		}
	}	
	
	printf("%d",cnt);
	return 0;
 } 

代码:

#include<iostream>
#include<cstdio>
#include<algorithm>

using namespace std;

struct node
{
    int s,e;
};
node a[1000010];
int cnt=1;
int n;
    
bool cmp(node aa,node bb)
{
    return aa.e<bb.e;
}

int main()
{
    cin>>n;
    for(int i=0;i<n;i++)
        cin>>a[i].s>>a[i].e;
    
    sort(a,a+n,cmp);
    
    int p=a[0].e;//第一段不用看,从1开始加 
    
    for(int i=1;i<n;i++)
    {
        if(a[i].s >= p)
        {
            cnt++;
            p=a[i].e;
        }
    }
    cout<<cnt;
    return 0;
}

结果:

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值