【题目描述】
学校在最近几天有n个活动,这些活动都需要使用学校的大礼堂,在同一时间,礼堂只能被一个活动使用。由于有些活动时间上有冲突,学校办公室人员只好让一些活动放弃使用礼堂而使用其他教室。
现在给出n个活动使用礼堂的起始时间begini和结束时间endi(begini<endi),请你帮助办公室人员安排一些活动来使用礼堂,要求安排的活动尽量多。
【输入】
第一行一个整数n(n≤1000);
接下来的n行,每行两个整数,第一个begini,第二个是endi(begini<endi≤32767)。
【输出】
输出最多能安排的活动个数。
【输入样例】
11
3 5
1 4
12 14
8 12
0 6
8 11
6 10
5 7
3 8
5 9
2 13
两种方法,一个贪心(按结束时间排序,再用贪心的思维去找结束时间最快的活动,),一个是动态规划(按开始的时间排序,再用动态规划的思维去做,就是,每加一个活动,就和前面的活动比较,然后再加天数)
下面是动态规划
#include <iostream>
#include <stdio.h>
#include <cstring>
#include <stdio.h>
#include <algorithm>
#include <cmath>
#define N 1001
using namespace std;
int n,cnt,vis[N],maxn;
struct action{
int begin,end;
} a[N];
void dfs(int x){
for(int i=x-1; i>=1; --i){
if(a[x].begin > a[i].end){
vis[i] = 1;
cnt++;
maxn = max(maxn, cnt);
dfs(i);
cnt--;
vis[i] = 0;
}
}
}
bool cmp(action x,action y){
if(x.begin == y.begin){
return x.end < y.end;
}
if(x.begin != y.begin){
return x.begin < y.begin;
}
}
int main(){
cin>>n;
for(int i=1; i<=n; ++i) {
cin>>a[i].begin>>a[i].end;
}
a[0].begin = 0;
a[0].end = 0;
int temp = -99999999;
sort(a+1, a+n+1, cmp);
for(int i=1; i<=n; ++i){
vis[i] = 1;
for(int j=1; j<i; ++j){
if( a[j].end <= a[i].begin && vis[j] + 1 > vis[i]){
vis[i] = vis[j] + 1;
}
}
temp = max(temp, vis[i]);
}
printf("%d",temp);
return 0;
}
下面是贪心
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#define INF 999999999
#define N 1001
using namespace std;
int n;
int beginn[N],endd[N];
void qsort(int x,int y)
{
int i,j,mid;
i=x;
j=y;
mid=endd[(x+y)/2];
while(i<=j)
{
while(endd[i]<mid)
i++;
while(endd[j]>mid)
j--;
if(i<=j)
{
swap(endd[j],endd[i]);
swap(beginn[j],beginn[i]);
i++;
j--;
}
}
if(x<j)
qsort(x,j);
if(i<y)
qsort(i,y);
}
int main()
{
cin>>n;
for(int i=1;i<=n;i++)
cin>>beginn[i]>>endd[i];
qsort(1,n);
int cnt=0;
int temp=-INF;
for(int i=1;i<=n;i++)
if(beginn[i]>=temp)
{
cnt++;
temp=endd[i];
}
cout<<cnt<<endl;
return 0;
}