Program design thinking Week3- job C- interval coverage

C- interval coverage

Description

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).
Covering the entire point, i.e., (1,2) + (3,4) may cover (1,4).
Input requirements n, t and n sections, minimum number of output sections.

Sample

input:
3 10
1 7
3 6
6 10

output:
2

Idea

First, the greedy algorithm is finalized, in considering only the interval [1, t], press the left border from small to large, if they are equal the Right border descending order, meet the conditions selected one by one interval, the interval select the best coverage wide, the largest inter-cell that is the right boundary interval ignore included (reflecting the greedy algorithm), this time interval only consider the left edge of the left edge of the line is less than the specified date. After selecting the line segment specified update left border, so that it covers the entire range. Every position should pay attention to when i start point of the loop the loop.

Summary

This question is done mentality slightly collapse, probably around four or five times reconstructed, the last AC ground is relatively metaphysics.
The basic idea is that the greedy algorithm, comply with the criteria for qualifying interval selection right boundary greatest. It is easy to consider the case of small, easily confused thinking, WA do not know where to re-write it again the result of AC
if WA can try the following data:

input:
6 10
1 5
2 6
3 4
4 5
7 10
2 3
output
3

input:
1 3
1 2
output:
-1

input:
4 100
21 50
50 81
1 20
80 99
output
-1

input:
3 6
2 3
4 5
6 6
output:
-1

If the T is used cin.sync_with_stdio (false) or scanf

Codes

#include<iostream>
#include<cstdlib>
#include<cstdio>
#include<algorithm>
using namespace std;


struct time {
	int a, b;
}tim[25001];
bool compare(time &x,time &y){
	if(x.a!=y.a)return x.a < y.a;
	else return x.b > y.b;
}
int main() {

	cin.sync_with_stdio(false);

	int n, t;
	cin >> n >> t;
	for (int i = 0; i < n; i++)
		cin >> tim[i].a >> tim[i].b;
	sort(tim, tim + n , compare);

	int count = 0, i = 0, end = 1;
	bool flag = false;
	while (i < n && tim[i].a <= end) {
		count++;
		int maxn = -1;
		while (i < n && tim[i].a <= end) {
			maxn = (maxn > tim[i].b ? maxn : tim[i].b);		//取最大区间
			i++;
		}
		i--;
		end = maxn;
		if (end >= t) {		//覆盖成功及时停止
			flag = true;
			break;
		}
		end++; i++;
	}
	if (flag) printf("%d\n",count);
	else printf("-1\n");

}

Published 21 original articles · won praise 5 · Views 787

Guess you like

Origin blog.csdn.net/weixin_44578615/article/details/104707333