最短路(SPFA + 前向星)

Problem Description

输入T,N分别代表有T条通道,和N个地点。接下来T行u,v,w分别表示u地点于v地点之间通道消费,有重复边

Sample Input

5 5
1 2 20
2 3 30
3 4 20
4 5 20
1 5 100

Sample Output

90

运用SPFA的几个要点:
1, 首先要建立一个队列里面要存能够更新其他点的点;
2, 首先要做初始化,所有的点都没有被标记过,并且每个点到起点的dist[i] = INF;
3, 将起点push into queue,之后把这个点进行标记说明这个点在队列里面,然后dist[起点] = 0;显然不是吗?
4, 对queue不为空作为条件进行while循环更新其他点;
while(!q.empty())
    {
        u = q.front();//首先把这个点从队列里面取出来;
        q.pop();
        vis[u] = 0;取出来之后这个点就不在队列里面了,所以标记取消;
        for(i = head[u]; ~i; i = Map[i].next)//与这个点相关的一些边
        {
            to = Map[i].to, w = Map[i].w;
            if(dist[to] > dist[u] + w)//如果能够更新,就更新;
            {
                dist[to] = dist[u] + w;
                if(!vis[to])//在更新的同时把新的能够更新其他点的点扔进queue
                {
                    vis[to] = 1;
                    q.push(to);
                }
            }
        }
    }
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <algorithm>
#include <queue>
#define INF 0x3f3f3f3f
#define sum 521
using namespace std;
struct node
{
    int to, w, next;
}Map[40005];
int n, head[1005];
int vis[1005], dist[1005];
void SPFA(int u)
{
    int i, to, w;
    queue<int> q;
    for(i = 1; i <= n; i++)
    {
        vis[i] = 0;
        dist[i] = INF;
    }
    vis[u] = 1;
    dist[u] = 0;
    q.push(u);
    while(!q.empty())
    {
        u = q.front();
        q.pop();
        vis[u] = 0;
        for(i = head[u]; ~i; i = Map[i].next)
        {
            to = Map[i].to, w = Map[i].w;
            if(dist[to] > dist[u] + w)
            {
                dist[to] = dist[u] + w;
                if(!vis[to])
                {
                    vis[to] = 1;
                    q.push(to);
                }
            }
        }
    }
    printf("%d", dist[1]);
}
int main()
{
    int T, u, v, w;
    while(scanf("%d%d", &T, &n) != EOF)
    {
        memset(head, -1, sizeof(head));
        int cnt = 0;
        while(T--)
        {
            scanf("%d%d%d", &u, &v, &w);
            Map[cnt].to = v;
            Map[cnt].w = w;
            Map[cnt].next = head[u];
            head[u] = cnt++;
            Map[cnt].to = u;
            Map[cnt].w = w;
            Map[cnt].next = head[v];
            head[v] = cnt++;
        }
        SPFA(n);
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值