会场安排问题(输出最少的会场数)—— 贪心算法
问题描述
Description
假设要在足够多的会场里安排一批活动,并希望使用尽可能少的会场。设计一个有效的贪心算法进行安排。 对于给定的k个待安排的活动,计算使用最少会场的时间表。
Input
输入数据的第一行有1 个正整数k(k≤10000),表示有k个待安排的活动。接下来的k行中,每行有2个正整数,分别表示k个待安排的活动开始时间和结束时间。时间以0 点开始的分钟计。
Output
输出一个整数,表示最少会场数。
Sample Input
5
1 23
12 28
25 35
27 80
36 50
Sample Output
3
解题思路
证明问题满足贪心选择性质和最优子结构性质
1.贪心选择性质:因为活动安排问题每次安排活动时只需要考虑之前安排过的活动,不需要关心以后要安排的活动。因此该问题满足贪心选择性质。
2.最优子结构与性质:第n个活动安排时求的最优解一定是在第n-1个活动安排时求的最优解的基础之上的。因此该问题满足最优子结构与性质。
只有满足了上述两条性质之后才可以使用贪心算法来求解问题。
贪心策略
1.定义一个结构体(或者类)用来保存需要安排活动的开始时间和结束时间。
2.按照开始时间的先后顺序进行排序, 开始时间早的排在前面。
3.定义一个整数数组(初始化为0,大小为会场个数),用于保存每个会场的结束时间
4.对于每一个活动遍历会场,直到找到一个会场结束时间小于此次活动开始的时间为止。
代码
C++
这里我是用了编译器自带的sort函数。真的快啊。比我写的排序函数快多了。所以直接用了自带的sort函数.
#include <iostream>
#include <algorithm>
using namespace std;
struct huichang
{
int s;
int f;
};
huichang t[10000+10];
int n;
bool cmp(huichang a, huichang b) {
return a.s < b.s;
}
int meeting() {
int count_chang = 0;
int *a = new int[n + 1]; //该数组于保存每个会场的结束时间
for (int i = 0; i < n+1; i++) {
a[i] = 0;
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
if (a[j] <= t[i].s) {
a[j] = t[i].f;
if (j >= count_chang + 1) //记录已使用了的会场个数
count_chang++;
break;
}
}
}
delete[]a;
return count_chang;
}
int main() {
cin >> n;
for (int i = 1; i <= n; i++) {
cin >> t[i].s >> t[i].f;
}
sort(t+1,t+n+1,cmp);
cout << meeting() << endl;
return 0;
}
JAVA
我写的 java程序和C++使用的是同样的方法,但不知道为什么在我学校的OJ上C++ 200ms 就A了
但是同样的java代码直接超了3000ms判T了
不得不吐槽一下java的sort()函数还要新建个类用起来太麻烦了。
import java.util.Scanner;
import java.util.Arrays;
import java.util.Comparator;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
HuiChang []t = new HuiChang[n+1];
for(int i=1;i<=n;i++)
t[i] = new HuiChang();
for(int i = 1;i<=n;i++){
t[i].s = sc.nextInt();
t[i].f = sc.nextInt();
}
MyComparator cmp = new MyComparator();
Arrays.sort(t,1,n+1,cmp);
System.out.println(meeting(t));
}
private static int meeting(HuiChang []t){
int count_chang = 0;
int n = t.length-1;
int []a = new int [n+1];
for(int i=0;i<a.length;i++) {
a[i] = 0;
}
for(int i=1;i<=n;i++) {
for(int j=1;j<=n;j++) {
if(a[j]<=t[i].s) {
a[j] = t[i].f;
if(j>=count_chang+1)
count_chang++;
break;
}
}
}
return count_chang;
}
}
class HuiChang {
public int s;
public int f;
}
class MyComparator implements Comparator<HuiChang>{
@Override
public int compare(HuiChang o1, HuiChang o2) {
if(o1.s > o2.s) return 1;
else return -1;
}
}
更多推荐


所有评论(0)