Time Limit: 1000MS | Memory Limit: 30000K | |
Total Submissions: 25582 | Accepted: 9369 |
Description
For example, if you want to exchange 100 US Dollars into Russian Rubles at the exchange point, where the exchange rate is 29.75, and the commission is 0.39 you will get (100 - 0.39) * 29.75 = 2963.3975RUR.
You surely know that there are N different currencies you can deal with in our city. Let us assign unique integer number from 1 to N to each currency. Then each exchange point can be described with 6 numbers: integer A and B - numbers of currencies it exchanges, and real RAB, CAB, RBA and CBA - exchange rates and commissions when exchanging A to B and B to A respectively.
Nick has some money in currency S and wonders if he can somehow, after some exchange operations, increase his capital. Of course, he wants to have his money in currency S in the end. Help him to answer this difficult question. Nick must always have non-negative sum of money while making his operations.
Input
For each point exchange rates and commissions are real, given with at most two digits after the decimal point, 10-2<=rate<=102, 0<=commission<=102.
Let us call some sequence of the exchange operations simple if no exchange point is used more than once in this sequence. You may assume that ratio of the numeric values of the sums at the end and at the beginning of any simple sequence of the exchange operations will be less than 104.
Output
Sample Input
3 2 1 20.0 1 2 1.00 1.00 1.00 1.00 2 3 1.10 1.00 1.10 1.00
Sample Output
YES
Source
解題思路:
spfa算法實際上是bellman——ford算法的隊列優化,在bellman——ford算法中,在不存在負環的情況下,每個點最多被鬆弛|V|-1次,如果我們一開始將源節點入隊,每次將被鬆弛且不在隊列的點放入隊列,如果存在負環,那麼將有點入隊次數超過|V|;
代碼:
這裏使用了前向星存儲原圖,題意要求的是正環,那麼初始所有dis爲0,每個點表示所能換到的錢;
#include<cstdio>
#include<queue>
#include<vector>
#include<cstring>
#define MAXN 105
using namespace std;
int info[MAXN],cnt[MAXN];
double dis[MAXN];
bool flag[MAXN];
int src=0;
int n;
double v;
vector<int> to,next;
vector<double>com,rate;
queue<int> q;
void init()
{
memset(info,-1,sizeof(info));
memset(cnt,0,sizeof(cnt));
memset(flag,false,sizeof(flag));
memset(dis,0,sizeof(dis));
next.clear();
to.clear();
com.clear();
rate.clear();
}
void add(int i,int j,double r,double c)
{
to.push_back(j);
next.push_back(info[i]);
info[i]=to.size()-1;
com.push_back(c);
rate.push_back(r);
}
bool spfa(int s,double v)
{
int src=s-1;
dis[src]=v;
q.push(src);
cnt[src]++;
flag[src]=true;
cnt[src]++;
while(!q.empty())
{
int d=q.front();
q.pop();
flag[d]=false;
for(int i=info[d];i!=-1;i=next[i])
{
if((dis[d]-com[i])*rate[i]>dis[to[i]])
{
dis[to[i]]=(dis[d]-com[i])*rate[i];
if(!flag[to[i]])
{
q.push(to[i]);
flag[to[i]]=true;
cnt[to[i]]++;
if(cnt[to[i]]>n)
return true;
}
}
}
}
if(dis[src]>v)
return true;
return false;
}
int main()
{
int m,s;
int a,b;
double c,d,e,f;
scanf("%d%d%d%lf",&n,&m,&s,&v);
init();
for(int i=0;i<m;i++)
{
scanf("%d%d%lf%lf%lf%lf",&a,&b,&c,&d,&e,&f);
add(a-1,b-1,c,d);
add(b-1,a-1,e,f);
}
if(spfa(s,v))
printf("YES");
else
printf("NO");
return 0;
}