Spfa+vector存图

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sugarbliss/article/details/82907121

有向无向,权值可负图 

#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e5;
int n,m;
int d[maxn],vis[maxn];
vector<pair<int,int> >E[maxn];
void init()
{
    for(int i = 0; i < maxn; i++) vis[i] = 0;
    for(int i = 0; i < maxn; i++) d[i] = 1e9;
    for(int i = 0; i < maxn; i++) E[i].clear();
}
void spfa()
{
    queue <int> Q;
        Q.push(1);
        while(!Q.empty())
        {
            int now = Q.front();
            Q.pop(); vis[now] = 0;    //从队列中弹出now , vis[now] 标记为未访问
            for(int j = 0; j < E[now].size(); j++)
            {
                int v = E[now][j].first;
                if(d[v] > d[now] + E[now][j].second)
                {
                    d[v] = d[now] + E[now][j].second;
                    if(vis[v]) continue;    //如果访问过了(也就是 已经在队列中),就不用再push
                    vis[v] = 1;
                    Q.push(v);
                }
            }
        }
}
int main()
{
    while(cin>>n>>m && n+m)
    {
        init();
        int a,b,x;
        for(int i = 0; i < m; i++)
        {
            cin >> a >> b >> x;
            E[a].push_back(make_pair(b,x));
            E[b].push_back(make_pair(a,x));
        }
        d[1] = 0; vis[1] = 1; spfa(); //求坐标1~n的最短路
        printf("%d\n",d[n]);
    }
    return 0;
}
/*
2 1
1 2 3
3 3
1 2 5
2 3 5
3 1 2
0 0
------------
3
2
*/

猜你喜欢

转载自blog.csdn.net/sugarbliss/article/details/82907121