洛谷 P2299 Mzc和体委的争夺战

                  洛谷 P2299 Mzc和体委的争夺战

题目背景

mzc与djn第四弹。

题目描述

mzc家很有钱(开玩笑),他家有n个男家丁(做过前三弹的都知道)。但如此之多的男家丁吸引来了我们的体委(矮胖小伙),他要来与mzc争夺男家丁。

mzc很生气,决定与其决斗,但cat的体力确实有些不稳定,所以他需要你来帮他计算一下最短需要的时间。

输入输出格式

输入格式:

第一行有两个数n,m.n表示有n个停留站,m表示共有m条路。

之后m行,每行三个数a_i ; b_i ; c_iaibici ,表示第a_iai 个停留站到第b_ibi 个停留站需要c_ici 的时间。(无向)

输出格式:

一行,输出1到n最短时间。

输入输出样例

输入样例#1: 复制
5 8
1 2 3
2 3 4
3 4 5
4 5 6
1 3 4
2 4 7
2 5 8
1 5 100
输出样例#1: 复制
11

说明

n leq 2500;m leq 2*10^5n2500m2105

由于mzc大大十分着急,所以他只能等待1s。

思路:单源最短路(我一般用SPFA)        难度:普及/提高-

#include<algorithm>
#include<cstdio>
#include<queue>
#define MAXN 0x7fffffff
#define M 200005
using namespace std;
queue<int> q;
int n, m, k;
int tot;
int dis[M], vis[M];
int to[M*2], net[M*2], head[M*2], cap[M*2];    //无向图,开两倍

void add(int u, int v, int w) {    //数组储存邻接链表
    to[++tot] = v; net[tot] = head[u]; head[u] = tot; cap[tot] = w;
    to[++tot] = u; net[tot] = head[v]; head[v] = tot; cap[tot] = w;
}

void spfa(int x) {    //SPFA函数
    for(int i = 1; i <= n; i++) vis[i] = 0, dis[i] = MAXN;    //初始化
    vis[x] = 1; dis[x] = 0; q.push(x);
    while(!q.empty()) {
        int y = q.front();
        q.pop(); vis[y] = 0;
        for(int i = head[y]; i; i = net[i]) {
            int t = to[i];
            if(dis[t] > dis[y]+cap[i]) {
                dis[t] = dis[y]+cap[i];
                if(!vis[t]) vis[t] = 1, q.push(t);
            }
        }
    }
}

int main() {
    scanf("%d%d", &n, &m);
    for(int i = 1; i <= m; i++) {
        int a, b, c;
        scanf("%d%d%d", &a, &b, &c);
        add(a, b, c);
    }
    spfa(1);
    printf("%d", dis[n]);
    return 0;
}
原文地址:https://www.cnblogs.com/v-vip/p/8641047.html