POJ - 1860(spfa判断正环)

题目链接

思路:
spfa求最长路,cnt[i]记录从s到达i点的路径上点的数量,
当到达某个点路径的点数cnt[i]大于n时,代表在求最长路时用到了正环从而得出有正环。

代码:

#include <iostream>
#include <queue>
#include <cstring>
#include <vector>
#define fastio ios::sync_with_stdio(false), cin.tie(NULL), cout.tie(NULL)
#define debug(a) cout << "debug : " << (#a) << " = " << a << endl

using namespace std;

typedef long long ll;
typedef pair<ll, ll> PII;

const int N = 110;
const int INF = 0x3f3f3f3f;
const double eps = 1e-6;
const int mod = 998244353;

int n, m, s;
double money;
int cnt[N]; //cnt[i]记录从s到达i点的路径上点的数量
bool vis[N];
vector<int> a[N];
double rate[N][N], cost[N][N], dis[N]; //rate为汇率,cost为手续费
bool spfa()
{
    memset(dis, 0, sizeof dis);
    memset(vis, false, sizeof vis);
    memset(cnt, 0, sizeof cnt);
    dis[s] += money;
    queue<int> q;
    cnt[s] = 1;
    //从s开始可能不会经过负环,所以一开始要先将所有点加入队列
    for (int i = 1; i <= n; i++)
    {
        q.push(i);
        vis[i] = true;
    }
    while (q.size())
    {
        int t = q.front();
        q.pop();
        vis[t] = false; //标记t点出队列
        for (int i = 0; i < a[t].size(); i++)
        {
            int j = a[t][i];
            if (dis[j] < (dis[t] - cost[t][j]) * rate[t][j])
            {
                dis[j] = (dis[t] - cost[t][j]) * rate[t][j];
                cnt[j] = cnt[t] + 1;
                if (cnt[j] > n)
                    return true;
                if (!vis[j])
                {
                    q.push(j);
                    vis[j] = true;
                }
            }
        }
    }
    return false;
}

int main()
{
    while (cin >> n >> m >> s >> money)
    {
        memset(rate, 0, sizeof rate), memset(cost, 0, sizeof cost);
        for (int i = 0; i < N; i++)
            a[i].clear();
        for (int i = 1; i <= m; i++)
        {
            int x, y;
            cin >> x >> y;
            a[x].push_back(y), a[y].push_back(x);
            cin >> rate[x][y] >> cost[x][y] >> rate[y][x] >> cost[y][x];
        }
        if (spfa())
            cout << "YES" << endl;
        else
            cout << "NO" << endl;
    }

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值