POJ-1860-Currency Exchange

这个题属于套汇问题,其实就是求一个图中是否存在环,比较简单,用spfa判断即可

代码:

#include<cstdio>
#include<cstring>
#include<iostream>
#include<queue>
using namespace std;
const int maxn=210;
const int maxm=102;
int e,n,m,s,head[maxm],pnt[maxn],nxt[maxn],cnt[maxm];
double v,cost[maxn],com[maxn],dist[maxm];
bool vis[maxm];
queue<int> q;
void AddEdge(int u,int v,double rate,double c)
{
    pnt[e]=v;nxt[e]=head[u];cost[e]=rate;com[e]=c;head[u]=e++;
}
bool Spfa(int st,double val)
{
    memset(dist,0,sizeof(dist));
    memset(vis,0,sizeof(vis));
    memset(cnt,0,sizeof(cnt));
    while(!q.empty())
	q.pop();
    dist[st]=val;
    cnt[st]=1;
    q.push(st);
    while(!q.empty())
    {
	int u=q.front();
	q.pop();
	vis[u]=0;
	for(int i=head[u];i!=-1;i=nxt[i])
	{
	    int v=pnt[i];
	    if(dist[v]<(dist[u]-com[i])*cost[i])
	    {
		dist[v]=(dist[u]-com[i])*cost[i];
		if(!vis[v])
		{
		    vis[v]=1;
		    q.push(v);
		    if(++cnt[v]>n)
			return true;
		}
	    }
	}

    }
    return false;
}
int main()
{
    while(scanf("%d%d%d%lf",&n,&m,&s,&v)!=EOF)
    {
	memset(head,-1,sizeof(head));
	e=0;	
	for(int i=0;i<m;i++)
	{
	    int u,v;
	    double x1,y1,x2,y2;
	    scanf("%d%d%lf%lf%lf%lf",&u,&v,&x1,&y1,&x2,&y2);
	    AddEdge(u,v,x1,y1);
	    AddEdge(v,u,x2,y2);
	}
	if(Spfa(s,v))
	    printf("YES\n");
	else
	    printf("NO\n");
    }
    return 0;
}


你可能感兴趣的:(最短路径,SPFA)