问题描述:
第一种,不限制会场,要求使得所用的会场最少,具体代码如下:
import java.util.Scanner;
public class HuoDongAnPai1 {
/**
* 不限制 会场 解决方案1:ture count++; false count--;
* 2016/4/26/21:09
* 软件1404班
* 秃小驴
*/
private static int[] hui;
private static boolean[] tag;
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int[] start = new int[n];
int[] finish = new int[n];
for (int i = 0; i < n; i++) {
start[i] = scanner.nextInt();
finish[i] = scanner.nextInt();
}
hui = new int[start.length + finish.length];
tag = new boolean[start.length + finish.length];
HuoDong(start, finish);
paixu(hui);
int count = 0;
int max = 0;
for (int i = 0; i < tag.length; i++) {
if (tag[i]) {
count++;
if (max < count) {
max = count;
}
}else {
count--;
}
}
System.out.println(max);
}
//合并数组
private static void HuoDong(int[] start,int[] finish){
for (int i = 0; i < start.length; ++i) {
hui[i] = start[i];
tag[i] = true;
}
for (int i = 0; i < finish.length; ++i) {
hui[i+start.length] = finish[i];
tag[i+finish.length] = false;
}
}
//数组排序
private static void paixu(int[] arr){
int temp = 0;
boolean t = true;
for (int i = 0; i < arr.length-1; i++) {
for (int j = i; j < arr.length; j++) {
if(arr[i] > arr[j]){
t = tag[i];
tag[i] = tag[j];
tag[j] = t;
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
}
}
第二种: 会场安排,一个会场要求活动最多:
思路:给每个活动的结束时间排序,然后 按照结束时间最早的开始比较,具体代码如下:
import java.util.Scanner;
public class HuoDongAnPai2 {
/**
* 背包问题 一个 会场 活动最多 解决方案2:
* 2016/4/26/21:56 软件1404班
* 秃小驴
*/
private static boolean[] tag;
private static int[] start;
private static int[] finish;
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
start = new int[n];
finish = new int[n];
for (int i = 0; i < n; i++) {
start[i] = scanner.nextInt();
finish[i] = scanner.nextInt();
}
tag = new boolean[n];
paixu(start, finish);
System.out.println(HuoDong(start, finish, tag));
for (int i = 0; i < tag.length; i++) {
System.out.println(tag[i]);
}
}
//会场一个 活动最多
private static int HuoDong(int[] start,int[] finish,boolean[] tag){
int count = 1;
tag[0] = true;
int j = 0;
for (int i = 1; i < tag.length; i++) {
if (start[i] >= finish[j]) {
tag[i] = true;
j = i;
count++;
}else {
tag[i] = false;
}
}
return count;
}
// 数组排序 按照活动结束的最早时间排序
private static void paixu(int[] start,int[] finish) {
int temp = 0;
int t = 0;
for (int i = 0; i < start.length - 1; i++) {
for (int j = i; j < start.length; j++) {
if (finish[i] > finish[j]) {
t = finish[i];
finish[i] = finish[j];
finish[j] = t;
temp = start[i];
start[i] = start[j];
start[j] = temp;
}
}
}
}
}