Meaning: Arbitrage. One US currency is exchanged for 0.5 British pound, and one British pound is exchanged for 10.0 French francs. At the same time, one French franc buys is 0.21 US dollar. so 1 US dollar can exchange 0.5*10.0*0.21 = 1.05 US dollars, and get 1.05us through a series of exchanges, then we can get the profit. Question: give some currencies and exchange rates, can I make a profit?
Question: here we can use the shortest method to solve the problem: we add the exchange rate to the edge struct, and then take a small value different from the shortest of the shortest, to make it profitable, we need to take a large value. When we initialize dis before spfa, We will assign a value to all memset values to 0 and DIS [SRC] source points to 1. in this way, we can relax the operation according to the above method, and then infer whether it constitutes a negative ring .. If yes, DIS will become larger and larger. spfa uses CNT [I] to represent the number of I queues. If the number of I queues is greater than the number of vertices, it indicates a negative ring.
Mount:
#include <iostream>#include <map>#include <string>#include <cstring>#include <queue>using namespace std;#define MAX 35int N,M;struct Edge{ int to,next; double rate;}edge[MAX*MAX];int head[MAX];void add(int u,int v,double rate,int i){ edge[i].to = v; edge[i].rate = rate; edge[i].next = head[u]; head[u] = i;}double dis[MAX];int cnt[MAX];bool flag[MAX];bool spfa(){ memset(flag,false,sizeof(flag)); memset(cnt,0,sizeof(cnt)); memset(dis,0,sizeof(dis)); dis[0] = 1; flag[0] = true; cnt[0] = 1; queue<int> q; q.push(0); while(!q.empty()) { int u = q.front(); q.pop(); flag[u] = false; for(int i = head[u]; i != -1; i = edge[i].next) { int v = edge[i].to; double rate = edge[i].rate; if(dis[v] < dis[u]*rate){ dis[v] = dis[u]*rate; if(!flag[v]){ q.push(v); flag[v] = true; cnt[v] ++; } } if(cnt[v] > N) return true; } } return false;}int main(){ string a,b; double rate; int cas = 1; while(cin >> N) { if(!N) break; map<string,int>m; for(int i = 0; i < N; i ++) { cin >> a; m[a] = i; } cin >> M; memset(head,-1,sizeof(head)); for(int i = 0; i < M; i ++){ cin >> a >> rate >> b; int u = (*m.find(a)).second; int v = (*m.find(b)).second; add(u,v,rate,i); } cout << "Case " << cas++ << ": "; if(spfa()) cout << "Yes" <<endl; else cout << "No" <<endl; } return 0;}