這道題的題意是:給出n種國家的貨幣匯率,必定金額的某種貨幣通過一系列匯率變換後再換成原來貨幣,金額增長了,求出這樣的一個變換,要求變換步數最少。java
因爲數據量不大,咱們能夠直接用動規+floyd解決,設f[p][i][j]爲由i到j通過p次轉換所能達到的最大匯率乘積,每循環一次p咱們就掃描一遍f[p][i][i],若是有大於1的狀況就直接打印結果便可。spa
在記錄路徑時用path[p][i][j]記錄第k次轉換的初始位置,打印時採用遞歸的方式。code
3
orm
1.2 .89
.88 5.1
1.1 0.15
4
3.1 0.0023 0.35
0.21 0.00353 8.13
200 180.559 10.339
2.11 0.089 0.06111
2
2.0
0.45遞歸
Sample Output
it
1 2 1
io
1 2 4 1
no arbitrage sequence existsclass
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.io.StreamTokenizer; public class Arbitrage { public static int n; public static float[][][] f; public static int[][][] path; public static void floyd() { int p, i, j, k; p = i = j = k = 0; for (p = 1; p < n; p++) { for (i = 0; i < n; ++i) for (j = 0; j < n; ++j) for (k = 0; k < n; ++k) {//找到f(p-1)到f(p)轉換的最大值保存下來,同時保存轉換路徑 if (f[p - 1][i][k] * f[0][k][j] > f[p][i][j]) { f[p][i][j] = f[p - 1][i][k] * f[0][k][j]; path[p][i][j] = k; } } for (int m = 0; m < n; ++m) { if (f[p][m][m] > 1) { // System.out.println("find some thing"); print(m, m, p); System.out.println(); } } } } public static void print(int i, int j, int p) { if (p == 0) { System.out.print(i+" ");//打印起點 System.out.print(j+" ");//打印起點後打印途徑點 } else { print(i, path[p][i][j], p - 1);//先遍歷到起點再開始打印 System.out.print(j+" ");//打印途徑點 } } public static void main(String[] args) { try { FileInputStream fis = new FileInputStream(new File("D:/a.txt")); StreamTokenizer st = new StreamTokenizer(new BufferedReader( new InputStreamReader(fis))); while (st.nextToken() != StreamTokenizer.TT_EOF) { System.out.println("-------"); n = (int) st.nval; f = new float[n][n][n]; path = new int[n][n][n]; for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { if (i == j) f[0][i][j] = 1; else { st.nextToken(); f[0][i][j] = (float) st.nval; } } } floyd(); } } catch (Exception e) { e.printStackTrace(); } } }