P1803 Messy yyy / line segment coverage (Luogu)

Original title portal

Insert picture description here
Insert picture description here
Idea: Interval greedy question, first define a structure to store the start and end times, then define a function to sort the end times from small to large, and then traverse each end time after sorting, the earlier the end is satisfied and the satisfaction Participate if the conditions are met, and finally output the number

Code reference

#include<bits/stdc++.h>
using namespace std;
struct Match//使用结构体将比赛的开始时间和结束时间保存下来
{
    
    
	int start;//开始时间
	int end;//结束时间
}M[1000000];
bool compare(Match x, Match y)//以结束时间从小到大排序
{
    
    
	return x.end < y.end;
}
int main()
{
    
    
	int n;
	cin>>n;
	for(int i=0;i<n;i++)
        cin>>M[i].start>>M[i].end;
	sort(M,M+n,compare);
	int pos = 0; //上一场比赛的结束时间
	int num=0;//能够参加比赛的次数
	for(int i=0;i<n;i++)
	{
    
    
		if(pos<=M[i].start)
		{
    
    
			pos = M[i].end;
			num++;
		}
	}
	cout<<num;
	return 0;
}

Guess you like

Origin blog.csdn.net/Bertil/article/details/106795129