(区间相关问题)洛谷P1803凌乱的yyy / 线段覆盖

这篇博客主要介绍了如何解决洛谷P1803题目中凌乱的线段覆盖问题。作者从算法分析角度出发,结合贪心思想,指出应先对线段右边界进行排序,以便选择更靠前的线段。文章接着提供了实现代码,详细展示了算法的具体步骤。

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

一、算法分析

可以联系紫书上的,选择不相交的区间那一节。本题算法很直观,从贪心思想来说,我们希望选的线段尽量靠前而给后面的线段腾出空间,所以就要对线段的右边界排序。然后尽量往左挤。

二、代码如下

#include<iostream>
#include<cstdio>
#include<cstring>
#include<vector>
#include<algorithm>
using namespace std;
int n;
struct edge{
	int from;
	int to;
	edge(int ff,int tt):from(ff),to(tt){}
};
vector<edge> a;
bool cmp(edge x1,edge x2){
	return x1.to<x2.to;
}
int main(){
	
	cin>>n;
	int ed=0;                                                      //保存当前的右界 
	int ans=0;
	int xx,yy;
	for(int i=0;i<n;i++){
		cin>>xx>>yy;
		a.push_back(edge(xx,yy));
	}
	
	sort(a.begin(),a.end(),cmp);
	
	for(int i=0;i<n;i++){
		if(a[i].from>=ed){
			ans++;
			ed=a[i].to;
		}
	}
	cout<<ans;
	return 0;
} 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值