[Problem solution] Line segment

Title source: loj

Title description

There are n line segments on the number line. Select k line segments so that the k line segments have no overlapping parts. Ask how much k is the largest.

Input format

The first line is a positive integer n;

In the next n rows, each row has 2 numbers ai, bi, describing each line segment.

Output format

Output an integer, which is the maximum value of k.

Sample input

3
0 2
2 4
1 3

Sample output

2

Ideas

It is the same as the event schedule, sorted from small to large according to the end of each line segment

code

#include<bits/stdc++.h>
using namespace std;
const int N=1e6+10;
int n,anss;
struct node{
    
    
	int st,ed;
}a[N];

void init()
{
    
    
	scanf("%d",&n);
	for (int i=1;i<=n;i++) scanf("%d%d",&a[i].st,&a[i].ed);
}

int cmp(node x,node y) {
    
     return x.ed<y.ed; }

void work()
{
    
    
	int ed=0;
	sort(a+1,a+1+n,cmp);
	for (int i=1;i<=n;i++)
		if (a[i].st>=ed) ed=a[i].ed,anss++;
}
int main()
{
    
    
	init();
	work();
	cout<<anss<<endl;
	return 0;
}

Guess you like

Origin blog.csdn.net/weixin_45485187/article/details/102817439