[Programming thinking and practice Week3 job C] interval coverage

Meaning of the questions:

There are a number line n (1 <= n <= 25000) a closed interval [ai, bi], selected to cover a range of as little as specified segment [1, t] (1 < = t <= 1,000,000).
-1 outputs the impossible.

Input:

First line: N T and the
second row N + 1 to row: each line a closed interval.

Sample Input:

3 10
1 7
3 6
6 10

Output:

Selected number of intervals, the output of the impossible -1

Sample Output:

2

Ideas:

To select as little as possible to cover the range of the target range, so each selected interval coverage as large as possible from the starting point of the interval (the reason why is because from the start if from the middle to select a larger range, then have to cover the head and tail You could use more range). Thus the left end in ascending order first section, then in accordance with the above greedy strategy selection interval, after the election, each time interval, the update interval of the target starting point (the end of the current interval has covered +1), repeat the previous step selection interval, until complete coverage of all target range.

Error-prone points:

1. covering the entire point, i.e., (1,2) and (3,4) may cover (1,4), each update target range when starting end to the last selected interval +1.
2. The start code while loop, the reason why the rside (right starting point, is pointing to the current role of the right endpoint of interval has covered) is set to 0 instead of 1, is because if the end of a target range, will not be found and terminates the count variable to 0, it should be set to 0 so rside.

Code:

#include <iostream>
#include<stdio.h>
#include<vector>
#include<algorithm>
using namespace std;
bool cmp(pair<int,int>&a,pair<int,int>&b)
{
	
	return a.first<b.first;
}

int main(int argc, char** argv) {
	int n,t;
	scanf("%d%d",&n,&t);
	vector<pair<int,int>> val(n);
	for(int i=0;i<n;i++)
	{
		scanf("%d%d",&val[i].first,&val[i].second);
	}
	sort(val.begin(),val.end(),cmp);
	int lside=1,rside=0,count=0;
	int i=0;
	while(rside<t)
	{
		while(i<n&&val[i].first<=lside)
		{
			if(rside<val[i].second)
				rside=val[i].second;
			i++;
		}
		if(rside<lside)
		{
			count=-1;
			break;
		}
		count++;
		lside=rside+1;
	}
	return 0;
}
Published 25 original articles · won praise 8 · views 540

Guess you like

Origin blog.csdn.net/weixin_44034698/article/details/104719752