题意:
给出各种货币之间的汇率,还有每次兑换的手续费。求这个人在经过多次兑换后,能否使自己的钱变多,注意变多是指钱的种类不变,数目变多。
思路:
spfa算法会比较好理解,按照题意只要找到正环,那么你的钱就会越换越多,最后肯定是可以换回本来的那种货币,不管手续费多高没事。因为数据小,我用了邻接矩阵储存数据,还有另外一种邻接表的方法我一并贴出来
邻接矩阵
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;
double ms[205][205];//手续费
double mr[205][205];//汇率
int n,m,s;
int vis[205],num[250];
double d[205],v0;
bool spfa(int s){queue<int>q;vis[s]=1;num[s]++;d[s]=v0;q.push(s);while(!q.empty()){int u=q.front();vis[u]=0;//注意出队列标记 q.pop();for(int v=1;v<205;v++){if(!mr[u][v]) continue;if((d[u]-ms[u][v])*mr[u][v]>d[v]){d[v]=(d[u]-ms[u][v])*mr[u][v];if(!vis[v]){vis[v]=1;q.push(v);//注意进队列 num[v]++;if(num[v]>n) return 1;//存在正环 }}}}
// if(d[s]>v0) return 1;
// else return 0; return 0;}
int main(){while(scanf("%d%d%d%lf",&n,&m,&s,&v0)!=EOF){memset(vis,0,sizeof(vis));memset(mr,0,sizeof(mr));memset(num,0,sizeof(num));memset(d,0,sizeof(d));int a,b;double ab_r,ab_s,ba_r,ba_s;for(int i=0;i<m;i++){scanf("%d%d%lf%lf%lf%lf",&a,&b,&ab_r,&ab_s,&ba_r,&ba_s);//注意double是lf输入,自己总是忘记 mr[a][b]=ab_r; ms[a][b]=ab_s;mr[b][a]=ba_r; ms[b][a]=ba_s;}if(spfa(s)) puts("YES");else puts("NO");} return 0;
}
邻接表
#include <iostream> #include <cstdio> #include <cstring> #include <stdlib.h> #include <math.h> #include <queue> #include <algorithm> using namespace std; #define N 210 #define INF 0xfffffff double dist[N], V; int cnt, Head[N], num[N], vis[N]; int n, m, s;struct Edge {int v, next;double r, c; }e[N];void Add(int u, int v, double r, double c) {e[cnt].v = v;e[cnt].r = r;e[cnt].c = c;e[cnt].next = Head[u];Head[u] = cnt++; }bool spfa()///spfa模板; {memset(vis, 0, sizeof(vis));memset(num, 0, sizeof(num));queue<int>Q;vis[s] = 1;dist[s] = V;Q.push(s);num[s]++;while(Q.size()){int p=Q.front();Q.pop();vis[p] = 0;for(int i=Head[p]; i!=-1; i=e[i].next){int q = e[i].v;if(dist[q] < (dist[p] - e[i].c) * e[i].r)///注意松弛的变化; {dist[q] = (dist[p] - e[i].c) * e[i].r;if(!vis[q]){vis[q] = 1;Q.push(q);num[q] ++;if(num[q]>n)return true;///存在正权回路; }}}}if(dist[s]>V)///最长路后,实现了增值;return true;return false; }int main() {int a, b;double rab, rba, cab, cba;while(scanf("%d%d%d%lf", &n, &m, &s, &V)!=EOF){cnt = 0;memset(Head, -1, sizeof(Head));memset(dist, 0, sizeof(dist));for(int i=1; i<=m; i++){scanf("%d%d%lf%lf%lf%lf", &a, &b, &rab, &cab, &rba, &cba);Add(a, b, rab, cab);Add(b, a, rba, cba);}if( spfa() )printf("YES\n");elseprintf("NO\n");}return 0; }