UVA104Arbitrage (floyd)
UVA104Arbitrage (floyd)
UVA104Arbitrage
Question:
The exchange rate between the two countries requires you to start from any country, carry 1 (Unit unknown), and then return to this country, the money can be> 1. 01. in addition, if there are multiple such paths, the shortest path is expected and you need to output the shortest path.
Solution:
Using floyd, you can find the greatest money you can get for traveling to any two countries, but you cannot get the shortest path. The shortest path means that the number of transit countries is as small as possible. Therefore, we need to add a dimension to mark the country I to j, and the country (including I) goes through the middle of p ). So G [I] [j] [p] = max (G [I] [j] [p ], G [I] [k] [p-1] * G [k] [j] [1 ]); and use path [I] [j] [p] to record the transit city.
Code:
#include
#include
const int maxn = 30;int n;int path[maxn][maxn][maxn];double table[maxn][maxn][maxn];void init () { memset(table, 0, sizeof(table)); memset(path, -1, sizeof(path)); for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) { if (i == j) { table[i][j][1] = 0; } else { scanf ("%lf", &table[i][j][1]); } }}int floyd (int &p) { for (p = 1; p < n; p++) for (int k = 0; k < n; k++) for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) { if (table[i][k][p] * table[k][j][1] > table[i][j][p + 1]) { table[i][j][p + 1] = table[i][k][p] * table[k][j][1]; path[i][j][p + 1] = k; } if (i == j && table[i][j][p + 1] > 1.01) return i; } return -1;}void print_path(int start, int end, int p) { int next = path[start][end][p]; if (next == -1) return; print_path(start, next, p - 1); printf("%d ", next + 1); print_path(next, end, 1);}int main () { while (scanf ("%d", &n) != EOF) { init(); int p; int start = floyd(p);// printf ("%d\n", start); if (start == -1) printf ("no arbitrage sequence exists\n"); else { printf ("%d ", start + 1); print_path(start, start, p + 1); printf ("%d\n", start + 1); } } return 0;}