week 3 B-interval point selection

topic:

There are n closed intervals [a_i, b_i] on the number line. Take as few points as possible so that there is at least one point in each interval (the points contained in different intervals can be the same)

Input:

1 integer N in the first line (N <= 100)
Line 2 ~ N + 1, two integers a, b in each line (a, b <= 100)

Output:

An integer representing the number of points selected

Examples:

Input

2
1 5
4 6

Output

1

Input

3
1 3
2 5
4 6

Output

2

Ideas:

The greedy strategy for this question is: select the last point of the interval. Sort all intervals by end from small to large, and when end is the same, sort by from large to small.
Proof:
1. When the interval contains, if there is a point in the cell, there must be a point in the large interval, so we should prefer to select the point in the cell, so that the large interval does not need to take points. If the interval contains the situation, the neighbouring cells will be selected preferentially when traversing according to this sorting method. In this case, the greedy strategy is correct.
2. When the starting points of the intervals are arranged in increasing order, the last point in the selection interval can obviously include more intervals. In this case, the greedy strategy is also correct.

Code:

#include <iostream>
#include <algorithm>

using namespace std;

struct zone
{
	int be;
	int end;
};

bool cmp(zone a, zone b)
{
	if (a.end == b.end)
		return a.be > b.be;
	return a.end < b.end;
}

int main()
{
	int be, end, n, count;
	while (scanf("%d",&n)!=EOF)
	{
		count = 1;
		zone *temp = new zone[n];
		for (int i = 0; i < n; i++)
		{
			cin >> be >> end;
			temp[i].be = be;
			temp[i].end = end;
		}
		sort(temp,temp+n,cmp);
		int j = 0;
		for (int i = 1; i < n; i++)
		{
			if (temp[i].be > temp[j].end)
			{
				j = i;
				count++;
			}
		}
		cout << count << endl;
	}
	return 0;
}


Published 32 original articles · praised 0 · visits 695

Guess you like

Origin blog.csdn.net/qq_43814559/article/details/104722851