OpenJ_Bailian - 4151 Film Festival (greedy)

The College Student Film Festival was held at Peking University! On this day, many films were shown all over Peking University. Given the screening time interval of each film, it is impossible to watch films with overlapping intervals at the same time (the endpoints can overlap). Ask Li Lei how much he can watch at most. movie.

Input
multiple sets of data. The beginning of each group of data is n (n<=100), which means a total of n movies.
The next n lines, each line has two integers (between 0 and 1000), indicating that the screening interval of a movie is
n=0, then the data ends.
Output
For each set of data output, you can watch at most several movies.
Sample Input
8
3 4
0 7
3 8
15 19
15 20
10 15
8 18
6 12
0
Sample Output
3

Thought analysis:

Typical greedy problem. As long as we choose the earliest and shortest movie to watch each time, we can watch the most movies.
Therefore, we sort the end time, and each time we select the interval with the earliest end time and does not overlap with the previous one, we can get the answer.

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

struct node{
    
    
	int s, e;
};

bool cmp(const node &a, const node &b)
{
    
    
	if(a.e == b.e) return a.s > b.s;
	return a.e < b.e;
}

int main()
{
    
    
	int n;
	node t;
	while(~scanf("%d",&n) && n)
	{
    
    
		node a[1010];
		for(int i = 0;i < n;i++)
		{
    
    
			scanf("%d%d",&a[i].s, &a[i].e);
		}
		sort(a,a+n,cmp);
		int idx = -1, cnt = 0;
		for(int i = 0;i < n;i++)
		{
    
    
			t = a[i];
			if(t.s >= idx) idx = t.e, cnt++;
		}		
		cout<<cnt<<endl;
	}
	return 0;
} 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325582777&siteId=291194637