1235: 会场安排问题
Description
学校的小礼堂每天都会有许多活动,有时间这些活动的计划时间会发生冲突,需要选择出一些活动进行举办。小刘的工作就是安排学校小礼堂的活动,每个时间最多安排一个活动。现在小刘有一些活动计划的时间表,他想尽可能的安排更多的活动,请问他该如何安排。
Input
第一行是一个整型数m(m<100)表示共有m组测试数据。
每组测试数据的第一行是一个整数n(1随后的n行,每行有两个正整数Bi,Ei(0<=Bi,Ei<10000),分别表示第i个活动的起始与结束时间(Bi<=Ei)
Output
对于每一组输入,输出最多能够安排的活动数量。
每组的输出占一行
Sample Input
221 1010 1131 1010 1111 20
Sample Output
12
思路:经典的贪心问题,sort+结构体;
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
struct node
{
int a;
int b;
}s[10000+10];
bool cmp(node x,node y)
{
if(x.b!=y.b)
return x.b<y.b;
else return x.a<y.a;
}
int main()
{
int t,n,i,j,k,max;
scanf("%d",&t);
while(t--)
{
k=1;
memset(s,0,sizeof(s));
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d %d",&s[i].a,&s[i].b);
}
sort(s,s+n,cmp);
max=s[0].b;
for(i=1;i<n;i++)
{
if(s[i].a>max)
{
k++;
max=s[i].b;
}
}
printf("%d\n",k);
}
return 0;
}
基准时间限制:1 秒 空间限制:131072 KB 分值: 10
难度:2级算法题
Input
第一行一个正整数n (n <= 10000)代表活动的个数。 第二行到第(n + 1)行包含n个开始时间和结束时间。 开始时间严格小于结束时间,并且时间都是非负整数,小于1000000000
Output
一行包含一个整数表示最少教室的个数。
Input示例
3 1 2 3 4 2 9
Output示例
2
类似的两个经典贪心问题,按照开始时间进行贪心;
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
typedef long long LL;
struct node {
int a;
int b;
bool c;
}s[10010];
bool cmp(node x, node y) {
if(x.a != y.a) return x.a < y.a;
return x.b < y.b;
}
int main() {
int n;
scanf("%d", &n);
for(int i = 0; i < n; i++) {
scanf("%d %d", &s[i].a, &s[i].b);
s[i].c = true;
}
sort(s, s + n, cmp);
int ans = 0;
for(int i = 0; i < n; i++) {
if(!s[i].c) continue;
ans++;
int cnt = s[i].b;
s[i].c = false;
for(int j = i + 1; j < n; j++) {
if(s[j].a >= cnt && s[j].c) {
s[j].c = false;
cnt = s[j].b;
}
}
}
printf("%d\n", ans);
return 0;
}