[模板] [单源最短路径]

1.链式向前星构图

https://blog.csdn.net/Zeolim/article/details/81741443

2.利用小顶堆性质贪心BFS求得最短路 

https://www.bilibili.com/video/av25829980?from=search&seid=15079366380719599656

3.STL PQ使用

https://blog.csdn.net/c20182030/article/details/70757660

#pragma GCC optimize(2)
#include <cstdio>
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <cctype>
#include <string>
#include <cstring>
#include <algorithm>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <ctime>
#include <vector>
#include <fstream>
#include <list>
#include <iomanip>
#include <numeric>
using namespace std;
typedef long long ll;

const int MAXN = 1e6 + 10;

int inf = 0x3f3f3f3f;

ll n, m, s, ans[MAXN];

struct EDGE
{
    ll next, to, val;
}edge[MAXN];

int head[MAXN] = {0}, cnt = 0;

void add(int x, int y, int z)
{
    edge[++cnt].next = head[x];
    edge[cnt].to = y;
    edge[cnt].val = z;
    head[x] = cnt;
}

struct bfsnode
{
    ll now, dis;
    
    bfsnode(ll x, ll y)
    {
        now = x;
        dis = y;
    }

    bool operator < (const bfsnode ret) const
    {
        return dis > ret.dis;
    }

};

priority_queue <bfsnode> PQ;

bool finded[MAXN];

void bfs(bfsnode x)
{
	PQ.push(x);
	
    while(! PQ.empty())
    {
        bfsnode B = PQ.top();

        PQ.pop();

        if( !finded[B.now] )
        {
            finded[B.now] = true;

            ans[B.now] = min(ans[B.now], B.dis);

            for(int i = head[B.now]; i != 0; i = edge[i].next)
            {
                PQ.push( bfsnode(edge[i].to, B.dis + edge[i].val) );
            }
        }
    }
}

int main()
{
    ios::sync_with_stdio(false);

    cin.tie(0);     cout.tie(0);

    cin>>n>>m>>s;

    ll a, b, c;
	
	memset(ans, 0x3f, sizeof(ans));
	
    for(int i = 0; i < m; i++)
    {
        cin>>a>>b>>c;

        add(a, b, c);
    }

    bfs(bfsnode(s, 0));

    for(int i = 1; i <= n; i++)
        ans[i] >= inf ? printf("2147483647 ") : printf("%d ", ans[i]);

    return 0;
}

最短路

猜你喜欢

转载自blog.csdn.net/Zeolim/article/details/81750085
今日推荐