-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathFerryLoading_UVa10261.java
117 lines (90 loc) · 2.44 KB
/
FerryLoading_UVa10261.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
package v102;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class FerryLoading_UVa10261 {
static StringBuilder sb;
static int nCars, carLength[], memo[][];
static int dp(int car, int portRem, int starboardRem)
{
if(car == nCars)
return 0;
if(memo[car][portRem] != -1)
return memo[car][portRem];
int port = 0, starboard = 0, curLen = carLength[car];
if(curLen <= portRem) //put in the port side
port = 1 + dp(car + 1, portRem - curLen, starboardRem);
if(curLen <= starboardRem) //put in the startboard side
starboard = 1 + dp(car + 1, portRem, starboardRem - curLen);
return memo[car][portRem] = Math.max(port,starboard);
}
static void print(int car, int portRem, int starboardRem)
{
if(car == nCars)
return;
int optimal = dp(car, portRem, starboardRem), curLen = carLength[car];
if(curLen <= portRem)
{
int port = 1 + dp(car + 1, portRem - curLen, starboardRem);
if(optimal == port)
{
sb.append("port\n");
print(car + 1, portRem - curLen, starboardRem);
return;
}
}
if(curLen <= starboardRem)
{
int starboard = 1 + dp(car + 1, portRem, starboardRem - curLen);
if(optimal == starboard)
{
sb.append("starboard\n");
print(car + 1, portRem, starboardRem - curLen);
return;
}
}
}
public static void main(String[] args) throws NumberFormatException, IOException
{
Scanner sc = new Scanner(System.in);
sb = new StringBuilder();
int tc = sc.nextInt();
while(tc-- > 0)
{
int L = sc.nextInt() * 100;
carLength = new int[500];
nCars = 0;
while(true)
{
int curLen = sc.nextInt();
if(curLen == 0)
break;
carLength[nCars++] = curLen;
}
memo = new int[nCars][L+1];
for(int i = 0; i < nCars; i++)
Arrays.fill(memo[i], -1);
sb.append(dp(0, L, L)+"\n");
print(0, L, L);
if(tc != 0)
sb.append("\n");
}
System.out.print(sb);
}
static class Scanner
{
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));}
public String next() throws IOException
{
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {return Integer.parseInt(next());}
}
}