Program design thinking Week3- job B- interval selected point

B- interval selected point

Description

With n closed interval [a_i, b_i] number line. Take as few points, such that each section has at least one point (the interval containing different points may be the same). N and n the number of required input intervals, the output of the selected point

Sample


    Input

    2
    1 5
    4 6

    Output

    1

    Input

    3
    1 3
    2 5
    4 6

    Output

    2


Idea

First of all press the right boundary ascending section, a right boundary the left edge of the same descending order. Setting a flag for each segment is determined whether the flag has a dot interval sequentially performed for each segment is determined, wherein if a bit has not taken the right boundary of the section is determined to a point, this point may be such that the interval contains maximizing the number, reflecting the greedy algorithm, and the interval after each interval, this point is also determined in these intervals, the change flag is, directly after the skip cycle.

Summary

The problem is one of range problems, the basic idea is greedy, greedy criterion for which compliance is not a little to the right boundary interval whichever point, maximize benefits, right after ordering, the point or zone behind them or less than other sections of the left margin, you can ensure that no interval is ignored.

Codes

#include <iostream>
#include <algorithm>
using namespace std;
int n;

struct time {
	int a;
	int b;
	bool flag = false;
}t[100];

bool compare(time x, time y) {
	if (x.b != y.b)return x.b < y.b;
	else return x.a > y.a;
}

int main()
{
	cin >> n;
	for (int i = 0; i < n; i++)
		cin >> t[i].a >> t[i].b;
	sort(t, t + n, compare);
	int count = 0;
	int i = 0;
	while (i<n) {
		if (t[i].flag) {
			i++; continue;
		}
		int b;
		if (i < n) { b = t[i].b; count++; t[i].flag = true; i++;  }
		int index = i;
		while (index < n) {
			if (t[index].b >= b && t[index].a <= b) {
				t[index].flag = true;
				index++;
			}
			else index++;
		}
	}
	printf("%d\n", count);

}


Published 21 original articles · won praise 5 · Views 785

Guess you like

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