poj3259:spfa解法

构建一个队列,将松弛成功且不在队列的点放入队列,每次出队一个点.直到队列为空,如果队列中的某个入队次数超过n次,就说明存在一个负环.

#include "vector"
#include "queue"
#include "iostream"
using namespace std;
const double inf = 10000000;
struct node
{
    int end;
    double time_cost;
};
typedef vector<double> D;
bool relax(int beg,int end,double cost, D &distance)
{
    if (distance[beg] + cost < distance[end])
    {
        distance[end] = distance[beg] + cost;
        return true;
    }
    return false;
}
bool spfa(int N,D&distance, vector<vector<node>>& head)
{
    queue<int> Q;
    vector<int> isinq(N+1, 0);
    vector<int> visited(N + 1, 0);
    distance[0] = 0;
    Q.push(0);
    isinq[0] = 1;
    while (!Q.empty())
    {
        int beg = Q.front();
        Q.pop();
        isinq[beg] = 0;//不在队列中
        for (auto it : head[beg])
        {
            if (relax(beg, it.end, it.time_cost, distance))
            {
                if (!isinq[it.end])
                {
                    Q.push(it.end);
                    isinq[it.end] = 1;
                    if (++visited[it.end] > N)
                        return true;
                }       
            }
        }
    }
    return false;
}
int main()
{
    int F, N, M, W;
    cin >> F;
    while (F--)
    {
        cin >> N >> M >> W;
        vector<vector<node>> head(N + 1);//N+1个点
        int S, E;
        double T;
        while (M--)//普通path
        {
            cin >> S >> E >> T;
            head[S].push_back({ E, T });
            head[E].push_back({ S, T });
        }
        while (W--)//虫洞 one_way
        {
            cin >> S >> E >> T;
            head[S].push_back({ E, -T });
        }
        int count = N;
        while (count--)
            head[0].push_back({count+1,0});

        //初始化
        auto it = head.begin();
           bool ispossible = false;
            D distance(N+1,inf);
            ispossible = spfa(N,distance,head);
            if (ispossible)
                cout << "YES" << endl;
            else
            cout << "NO"<<endl;
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值