Week3: Interval choice of site - local greed

Setpoint range

Title Description
logarithmic axis with n closed interval [a_i, b_i]. Take as few points, such that have at least one point (point may be different sections containing the same) in each interval

Input format
of the first row an integer N (N <= 100)
of 2 ~ N + 1 lines, each two integers a, b (a, b < = 100)

Output formats
an integer representing the number of selected points

Sample

Input
2
1 5
4 6

Output
1

Input
3
1 3
2 5
4 6

Output
2

Problem-solving ideas
this question take partial greedy strategy.
For each section after the completion of the input, sort them:

  • Section ahead of the end of the smaller
  • When the end of the same section, the head section at the front of the larger

The next section is explained with an example (FIG accordance with such rules have been sorted good):
Show

  1. We chose a range of end point, then the total points count = 1. Not difficult to find, when the first click at this time, all its sections are the same end point will be a little bit (because we have sorted a), the setting here to curlast point.
  2. Next look after the interval, at this time, if the start point range encountered before our current curlast, then you can skip this section no matter, because there is already a point within its range of. (Figure as section 2 and section 3, this time we are still in the red at the point curlast)
  3. Read on, we found that when we encounter the interval 6, the start point just after curlast, and that is, curlast point can not meet "section 6 there is a point," so we need to choose the second point, we still choose to end point. At this time, count = 2, curlast blue position.
  4. Read on, start point range 7 before curlast point skipped.
  5. 8 interval start point after curlast point, so we operate with two previous update curlast. Now count = 3, curlast green place.
  6. We have found that traverse all over the range, end code, the result is 3;

Code

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

struct TimeCell
{
	int start;
	int end;

	TimeCell(int s,int e)
	{
		start = s;
		end = e;
	}
};

vector<TimeCell>timecell;

bool cmp(const TimeCell& a, const TimeCell& b)
{
	if (a.end != b.end) return a.end < b.end;
	else return a.start > b.start;
}

int main()
{
	int n, counter = 0;
	cin >> n;

	int tema, temb;
	for (int i = 0; i < n; i++)
	{
		cin >> tema >> temb;
		timecell.push_back(TimeCell(tema, temb));
	}

	sort(timecell.begin(), timecell.end(), cmp);

	int curlast = timecell[0].end;
	counter++;

	for (int i = 1; i < timecell.size(); i++)
	{
		if (curlast < timecell[i].start)
		{
			curlast = timecell[i].end;
			counter++;
		}
	}

	cout << counter << endl;

	return 0;
}
Published 21 original articles · won praise 3 · Views 418

Guess you like

Origin blog.csdn.net/qq_44506233/article/details/104702237