Til the Cows Come Home POJ - 2387 单源最短路 SPFA实现

本文介绍了一道经典的最短路径问题,并通过SPFA算法实现解答。文章分享了作者在实现过程中的经验教训,如如何避免负环及重边的判断。

题目:https://vjudge.net/problem/POJ-2387

好久没写博客了,算自己懒吧。

最短路入门题,自己练习用SPFA实现了下,不需要判负环也写上了。WA了好几次,忘记判断重边了。

代码:C++

//SPFA
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <algorithm>
#include <set>
#include <map>
using namespace std;

const int maxn = 2000 + 10;
const int INF = 2147483647;

map<int, map<int, int> > pic;

int T, n;

queue<int> q;
bool inq[maxn];
int cnt[maxn];

int dis[maxn];

void init()
{
    memset(cnt, 0, sizeof(cnt));
    memset(inq, false, sizeof(inq));
    for(int i = 1; i <= n; i++)
    {
        dis[i] = INF;
    }
    dis[1] = 0;
}

bool SPFA()
{
    q.push(1);
    inq[1] = true;
    cnt[1]++;
    while(!q.empty())
    {
        int cur = q.front();
        q.pop();
        inq[cur] = false;
        for(map<int, int>::iterator iter = pic[cur].begin(); iter!=pic[cur].end(); iter++)
        {
            if(dis[cur]!=INF && dis[cur] + iter->second < dis[iter->first])
            {
                dis[iter->first] = dis[cur] + iter->second;
                if(!inq[iter->first])
                {
                    q.push(iter->first);
                    cnt[iter->first]++;
                    inq[iter->first] = true;
                    //判断负环
                    if(cnt[iter->first] > n)
                    {
                        return false;
                    }
                }
            }
        }
    }
    return true;
}

int main()
{
    scanf("%d%d", &T, &n);
    init();
    while(T--)
    {
        int x, y, w;
        scanf("%d%d%d", &x, &y, &w);
        if(!pic[x].count(y))
        {
            pic[x][y] = w;
            pic[y][x] = w;
        }
        else
        {
            pic[x][y] = min(w, pic[x][y]);
            pic[y][x] = min(w, pic[y][x]);
        }
    }
    SPFA();
    printf("%d\n", dis[n]);
    return 0;
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值