-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathP104.java
105 lines (96 loc) · 3.04 KB
/
P104.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
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Scanner;
public class P104 {
public static void main(String[] args) throws IOException {
double[][][] table = new double[20][20][20];
byte[][][] back = new byte[20][20][20]; // from (i,j,k) = l used in computation below
BufferedReader rd = new BufferedReader(new InputStreamReader(System.in));
String line;
while(null != (line = rd.readLine())) {
if(line.trim().isEmpty())
return;
// Parse input:
Scanner s = new Scanner(line);
byte n = s.nextByte();
System.err.println("Start for " + n);
/*
table: Best currency conversion rates as:
iteration -> start currency -> end currency
where:
iteration: i = transactions (so up to n transactions in total)
*/
// Fill first iteration with input values:
for(byte i = 0; i < n; ++i) {
line = rd.readLine();
s = new Scanner(line);
for(byte j = 0; j < n; j++) {
if(i == j) {
table[0][i][j] = 0;
continue;
}
String st = s.next();
if(st.charAt(0) == '.')
st = "0" + st;
table[0][i][j] = Double.parseDouble(st);
}
}
boolean found = false;
byte bestIteration = 0;
byte bestCurrency = 0;
// Compute all iterations:
for(byte i = 1; i < n; ++i) { // i = iteration
if(found) break;
for(byte j = 0; j < n; ++j) { // j = from
if(found) break;
for(byte k = 0; k < n; ++k) { // k = to
if(found) break;
//System.err.println(i + " Check " + j + " to " + k);
table[i][j][k] = 0;
for(byte l = 0; l < n; ++l) { // l = middle step tryout.
if(l == k) { // Can't do conversion from selv to self.
continue;
}
double newVal = table[i-1][j][l] * table[0][l][k];
if(table[i][j][k] < newVal) {
table[i][j][k] = newVal;
back[i][j][k] = l;
//System.err.println(i + " " + j + "..." + l + "->" + k + ": " + table[i-1][j][l] +"*"+ table[0][l][k]);
if(newVal > 1.01 && j == k) {
found = true;
bestCurrency = j;
bestIteration = i;
break;
}
}
}
}
}
}
// Evaluate result:
if(!found) {
System.out.println("no arbitrage sequence exists");
continue;
}
LinkedList<Byte> stack = new LinkedList<Byte>();
byte c = bestCurrency;
stack.addFirst(c);
for(int i = bestIteration; i > 0; --i) {
c = back[i][bestCurrency][c];
stack.addFirst(c);
}
stack.addFirst(bestCurrency);
boolean first = true;
for(byte i : stack) {
if(!first) {
System.out.print(" ");
}
System.out.print(i+1);
first = false;
}
System.out.println();
}
}
}