Poj-2240-arbitrage (Bellman-ford algorithm exercise + Floyd algorithm exercise)

Source: Internet
Author: User
Tags cas
Arbitrage
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 20761 Accepted: 8846

Description Arbitrage is the use of discrepancies in currency exchange rates to transform one unit of a currency into more than one unit of the same currency. For example, suppose that 1 US Dollar buys 0.5 British pound, 1 British pound buys 10.0 French francs, and 1 French franc Buys 0.21 US dollar. Then, by converting currencies, a clever trader can start with 1 US dollar and buy 0.5 * 10.0 * 0.21 = 1.05 US dollars, MA King a profit of 5 percent.

Your job is to write a program this takes a list of currency exchange rates as input and then determines whether arbitrage is possible or not.

Input the input would contain one or more test cases. Om the first line of all test case there was an integer n (1<=n<=30), representing the number of different Currencie S. The next n lines each contain the name of one currency. Within a name no spaces would appear. The next line contains one integer m, representing the length of the table to follow. The last m lines all contain the name CI of a source currency, a real number Rij which represents the exchange rate from CI to CJ and a name CJ of the destination currency. Exchanges which do not appear in the table is impossible.
Test cases is separated from a blank line. Input is terminated by a value of zero (0) for N.

Output for each test case, print one line telling whether arbitrage are possible or not in the format "case Case:yes" resp ectively "Case Case:no".

Sample Input

3
USDollar
britishpound
frenchfranc
3
USDollar 0.5 britishpound
britishpound 10.0 Frenchfranc
Frenchfranc 0.21 USDollar

3
USDollar
britishpound
frenchfranc
6
USDollar 0.5 britishpound
USDollar 4.9 frenchfranc
britishpound 10.0 frenchfranc britishpound
1.99 USDollar
Frenchfranc 0.09 britishpound
frenchfranc 0.19 USDollar

0

Sample Output

Case 1:yes

Case 2:no


Test instructions

It is known that n currencies, as well as the exchange rate and mode of M currencies, ask whether the currency can be converted to increase wealth.


Title Link: Arbitrage


Problem Solving Ideas:

Visual inspection is a good make money ~ ~ ~ (STOP)


The wealth of the words must be compared with the same currency, otherwise there is no meaning, so test instructions can be roughly into a n vertex in the figure could find a positive weight ring, where the positive ring refers to the wealth increase, it is obvious that the Bellman-ford algorithm (specifically to solve the problem of the shortest path of existence ring).


Bellman-ford algorithm: A graph with n vertices if there is no ring, then from Vertex x, to Vertex y, up to the n-1 edge (to consider connectivity, each vertex up to 1 times), so the shortest possible X-to-y is up to n-1 relaxation operation (that is, the update length) should appear, if the first N times relaxation can also be optimal, then this diagram is definitely the existence of the ring (directly with Dijkstra can not be optimal, the existence of the ring will affect the existence of the optimal solution).


Here gives the vertex when the English name of the currency, in order to facilitate brevity, with a map of the currency name and number one by one corresponding


This problem has a variety of solutions, noted that the maximum vertex is 30 (limited, is not really a template exercise), can be used Floyd algorithm to find the shortest circuit of the entire graph, note here is not the true shortest, but through the insertion point, that is, I-J can be changed to K-J Road, Will consider the ring at least once, then the corresponding path[i][i] is the principal is definitely increased (relative to the initial value), for convenience, the principal is set to 1.


Code

Bellman_ford implementation:

Bellman_ford #include <cstdio> #include <cstring> #include <string> #include <algorithm> #
include<iostream> #include <vector> #include <map> using namespace std;
int n,m;    Double dist[40];
    Note that the type is double struct edge//edge structure, ST for the starting point, Ed for the end, RT for the exchange rate {int st,ed;
    Double RT;

Edge (int sst,int eed,double RTT): St (SST), Ed (eed), RT (RTT) {} edge () {}};
Vector<edge> G;

Map<string,int> MP;
    BOOL Bellman_ford (int v) {memset (dist,0,sizeof (Dist));
    DIST[V] = 1;  for (int j = 1;j < n;j++) {//n-1 times slack operation for (int i = 0;i < G.size (); i++) {int p1 = G[i].st,p2
            = G[i].ed;
            if (DIST[P2] < DIST[P1] * g[i].rt) {//try to update the distance from vertex v to p2 dist[p2] = dist[p1] * G[I].RT;
        }}} for (int i = 0;i < G.size (); i++) {int p1 = G[I].ST,P2 = G[i].ed;    
        if (DIST[P2] < DIST[P1] * g[i].rt) {//n-th relaxation can get better solution, then there is a loop return true;
 }   } return false;
    } int main () {int cas = 1;
    String S,ss;
            while (~SCANF ("%d", &n) &&n) {for (int i = 0;i < n;i++) {cin >> S; Mp[s] = i;
        The vertex number of currency name S is i} cin >> m;
        String beg,ends;
        Double R;
        G.clear ();    for (int i = 0;i < m;i++) {cin >> beg >> R >> ends;
        Edge Information Read G.push_back (Edge (Mp[beg], mp[ends], R));
        } printf ("Case%d:", cas++); for (int i = 0;i < n;i++) {//Enumerate all starting start if (Bellman_ford (i)) {//presence ring cout << "Yes" &L
                t;< Endl;
                printf ("Bellman%d\n", i);
            Break
        } else if (i = = n-1) cout << "No" <<endl;
}} return 0; }


Floyd algorithm:

floyed #include <cstdio> #include <cstring> #include <string> #include <algorithm> #include
<iostream> #include <vector> #include <map> using namespace std;
int n,m;
Double dist[40][40];

Map<string,int> money; void Init () {for (int i = 0;i < n;i++) {for (int j = 0;j < n;j++) {if (i = = j) Dist[i][j] = 1
            ;
        else dist[i][j] = 0; }}} void Floyd () {for (int k = 0;k < n;k++) {for (int i = 0;i < n;i++) {for (int j = 0;j < n;j++) {if (Dist[i][j] < dist[i][k] * Dist[k][j]) dist[i][j] = Dist[i][k]
            * DIST[K][J];
    }}}} int main () {int cas = 1;
    String S,ss;
    Double R;
        while (~SCANF ("%d", &n) &&n) {init ();
            for (int i = 0;i < n;i++) {cin >> S;
        Money[s] = i;

        } cin >> m;
  for (int i = 0;i < m;i++) {          Cin >> S >> r >> SS;
        Dist[money[s]][money[ss]] = r;
        } Floyd ();
        printf ("Case%d:", cas++);
                for (int i = 0;i < n;i++) {if (Dist[i][i] > 1) {cout << "Yes" << Endl;
            Break
        } else if (i = = n-1) cout << "No" <<endl;
}} return 0; }


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.