week 3 C-interval coverage

topic:

There are n (1 <= n <= 25000) closed intervals [ai, bi] on the number line. Choose as few intervals as possible to cover a specified line segment [1, t] (1 <= t <= 1,000,000).
Cover the whole point, ie (1,2) + (3,4) can cover (1,4).
Impossible to do output -1

Input:

The first line: the
second line of N and T to the N + 1 line: each line has a closed interval.

Output:

The number of selected intervals cannot be output -1

Examples:

Input
3 10
1 7
3 6
6 10

Output
2

hint:

This question has a lot of input data, please use scanf instead of cin

Ideas:

The greedy strategy for this question is: the interval selected each time is the interval with the largest end point including the current starting point.
Sort the intervals according to be from small to large. If the starting point of interval 1 is not less than or equal to 1, then there is no solution, otherwise the starting point is selected in the interval including the end point with the largest number. After selecting this interval [1, tempered], the new starting point should be set to temperen + 1, and look again for the segment with the largest end point including temperen + 1. Repeat this way until the time> = t or no interval is available.

Note: The
whole point is covered, that is, (1,2) and (3,4) can cover (1,4), and each time the start of the target interval is updated, it should be +1 for the end of the last selected interval.

Code:

#include <iostream>
#include <algorithm>

using namespace std;

struct zone
{
	int be;
	int end;
};

bool cmp(zone a, zone b)
{
	return a.be < b.be;
}

int main()
{
	int count, n, t;
	while (scanf("%d %d",&n,&t)!= EOF)
	{
		count = 0;
		zone *temp = new zone[n];
		for (int i = 0; i < n; i++)
			scanf("%d %d", &temp[i].be, &temp[i].end);
		sort(temp, temp + n, cmp);
		int tempbe = 0, tempend = 0, index = 0;
		while (tempend < t)
		{
			tempbe = tempend + 1;
			for (int i = index; i < n; i++)
			{
				if (temp[i].be <= tempbe)
				{
					tempend = max(temp[i].end, tempend);
				}
				else
				{
					index = i;
					break;
				}
			}
			if (tempbe <= tempend)
				count++;
			else
				break;
		}
		if (tempend >= t)
			cout << count << endl;
		else
			cout << "-1" << endl;
	}
	return 0;
}
Published 32 original articles · praised 0 · visits 694

Guess you like

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