Til the Cows Come Home POJ - 2387 单源最短路 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;
}

猜你喜欢

转载自blog.csdn.net/Rewriter_huanying/article/details/75948194