题目:
有最多15件事,分给两个人做。一个人不能同时做两件事,即分给同一个人的事情在时间上不能重叠。求两个人最多可以做多长时间的事情。
要求:
每件事情有开始时间和结束时间,时间由时、分两部分构成,输出以分钟为单位。
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Working {
static int[][] works;
static int[] seq;
static int n;
static int max;
public static void main(String[] args) throws FileNotFoundException {
// TODO Auto-generated method stub
@SuppressWarnings("resource")
Scanner sc = new Scanner(System.in);
sc = new Scanner(new File("files/working"));
int T = sc.nextInt();
for (int t = 0; t < T; t++) {
n = sc.nextInt();
works = new int[n][3];
seq=new int[n];
int hour, sec;
for (int i = 0; i < n; i++) {
hour = sc.nextInt();
sec = sc.nextInt();
works[i][0] = hour * 60 + sec;
hour = sc.nextInt();
sec = sc.nextInt();
works[i][1] = hour * 60 + sec;
works[i][2] = works[i][1] - works[i][0];
}
Qsort(0, n - 1, works);
max = 0;
dfs(0, 0, 0, 0);
System.out.println(max);
}
}
private static void dfs(int step, int time, int last1, int last2) {
// TODO Auto-generated method stub
if (step == n) {
if (time > max) {
max = time;
}
return;
}
if(Res()<=max-time)
return;
// 嫁给第一个人
if (works[step][0] >= last1) {
seq[step]=1;
dfs(step + 1, time + works[step][2], works[step][1], last2);
}
// 嫁给第二个人
if (works[step][0] >= last2) {
seq[step]=2;
dfs(step + 1, time + works[step][2], last1, works[step][1]);
}
// 孤独终生
seq[step]=3;
dfs(step + 1, time, last1, last2);
seq[step]=0;
}
private static int Res() {
// TODO Auto-generated method stub
int sum=0;
for(int i=0;i<n;i++){
if(seq[i]==0)
sum+=works[i][2];
}
return sum;
}
private static void Qsort(int l, int r, int[][] w) {
// TODO Auto-generated method stub
if (l < r) {
int[] key = new int[3];
CopyOf(key, w[r]);
int i = l;
int j = r;
while (i < j) {
while (i < j && w[i][0] < key[0])
i++;
CopyOf(w[j], w[i]);
while (i < j && w[j][0] >= key[0])
j--;
CopyOf(w[i], w[j]);
}
CopyOf(w[j], key);
Qsort(l, j - 1, w);
Qsort(j + 1, r, w);
}
}
private static void CopyOf(int[] s1, int[] s2) {
// TODO Auto-generated method stub
for (int i = 0; i < s1.length; i++) {
s1[i] = s2[i];
}
}
}
sample input:
5
5
8 0 14 0
9 0 12 0
13 0 18 0
10 0 17 0
10 30 13 30
6
8 0 18 10
13 10 15 20
10 50 13 30
13 20 18 10
12 0 12 50
12 0 15 30
8
10 40 12 20
9 10 15 10
11 0 16 30
11 50 15 50
8 30 13 50
15 0 18 10
9 30 10 10
13 10 18 30
10
10 50 13 50
9 40 12 0
8 20 15 10
8 30 10 20
11 40 13 20
8 20 13 50
14 20 18 10
15 0 16 40
8 0 16 50
10 0 11 10
14
10 40 15 50
9 40 10 0
12 40 16 10
12 40 13 0
12 20 17 40
11 40 17 30
9 0 12 0
16 10 17 30
17 0 18 40
8 40 12 40
8 20 14 30
12 40 18 40
15 0 16 20
9 40 10 10
sample output:
900–[0, 1, 2, 0, 1]
950–[1, 0, 0, 2, 0, 2]
970–[1, 0, 2, 2, 0, 0, 2, 1]
1090–[1, 2, 0, 0, 0, 0, 0, 0, 2, 0]
1150–[1, 2, 0, 0, 0, 0, 0, 0, 0, 2, 0, 1, 0, 1]