Juju's lessons

Juju's lessons

Time Limit:1000MS  Memory Limit:65536K
Total Submit:209 Accepted:40

Description

Juju is a child who enjoys learning. she has two majors and many courses have time conflict.As a child who love to learn, she wants to take lessons as many as she can. There are each lesson's start time and end time. She wants to know how many lessons can be taked after she master the replication.

Input

Input contains multiple test cases. 
The first line of each test case contains one interger n(1 <= n <= 100),the numbers of lesson. 
Next n lines have two integers a, b. (1 <= a < b <= 1000),the start time and the end time of each lesson.

Output

For each test case, Print a line, the numbers of lessons she can take.

Sample Input

2
1 3
4 5
3
1 4
3 5
2 3

Sample Output

2
2

题意:有n个区间,问最多可以选择几个区间使得这些区间除顶点外不重合。

题解:我们先对这些区间排序,接着用dp[i]表示前i个区间最多可以选择几个区间,那么当第i+1个区间出现时,我们只需要在前i个区间里找到与这个区间不重合的区间并且dp[j]最大的那个,然后连上去就可以了。即dp[i]=max{dp[j]|j<i&&第i个区间和第n个区间没有除顶点外的交集}+1.

代码:

//************************************************************************//
//*Author : Handsome How                                                 *//
//************************************************************************//
//#pragma comment(linker, "/STA	CK:1024000000,1024000000")
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <algorithm>
#include <sstream>
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <ctime>
using namespace std;
typedef long long ll;
//----------------------------------------------------------

int N;
struct Node{
	int l,r;
}node[105];
int dp[105];

bool cmp(Node a,Node b){
	if(a.l!=b.l)return a.l<b.l;
	return a.r<b.r;
}
int main()
{
	node[0].l=-1;node[0].r=-1;
	while(cin>>N){
		for(int i = 1;i<=N;i++)
			cin>>node[i].l>>node[i].r;
		sort(node+1,node+1+N,cmp);
		for(int i=1;i<=N;i++){
			int maxn = 0;
			for(int j=1;j<i;j++){
				if(node[j].r<=node[i].l)maxn=max(maxn,dp[j]);
			}
			dp[i]=1+maxn;
		}
		cout<<dp[N]<<endl;
	}
	return 0;
}


你可能感兴趣的:(Juju's lessons)