spfa 汇率转换

题目链接:

http://acm.hdu.edu.cn/showproblem.php?pid=1217

分析:普通的spfa 不过要注意是要向大的转换,且初始化 dis[s] 要赋一个正数代表初始的金钱数

#include <cstring>
#include <iostream>
#include <queue>
#include <cstdio>
#include <vector>
#include <map>
#include <cstring>
#include <string>
using namespace std;
#define maxn 1050
int N,M;
double G[maxn][maxn];
double dis[maxn];
int inq[maxn];
int times[maxn];
map<string,int>ma;
void init()
{
    memset(inq,0,sizeof(inq));
    memset(times,0,sizeof(times));
    for(int i = 0 ; i <= N ; ++i)dis[i] = -1;
    for(int i = 0 ; i <= N ; ++i)
        for( int j = 0 ; j <= N ; ++j)
            G[i][j] = 0;
}
void read()
{
    string st,str;
    for(int i = 1 ; i <= N ; ++i)
    {
        cin >> st;
        ma[st] = i;
    }
    cin >> M;
    for( int i = 1 ; i <= M ; ++i)
    {
        double a;
        cin >> st >> a >> str;
        G[ma[st]][ma[str]] = a;
    }
}

int spfa()
{
    queue<int>Q;
    int s = 1;
    Q.push(s);
    inq[s] = 1;
    dis[s] = 1;//此处赋初始金钱
    while(!Q.empty())
    {
        int u = Q.front();
        Q.pop();
        inq[u] = 0;
        for(int i = 1 ; i <= N ; ++i)
        {
            if(G[u][i])
            {
                int v = i;
                if(dis[v] < dis[u]*G[u][i] )//此处注意不同
                {
                    dis[v] = dis[u]*G[u][i];
                    if( !inq[v] )
                    {
                        Q.push(v);
                        inq[v] = 1;
                        times[v]++;
                        if( times[v] > N )
                            return 1;                       
                    }
                }

            }
        }
    }
    return 0;
}

int main()
{
    int k = 1;
    while(cin >> N && N)
    {
        init();
        read();
        printf("Case %d: ",k++);
        if( spfa() ) cout << "Yes" << endl;
        else cout << "No" << endl;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值