HihoCoder

描述

万圣节的晚上,小Hi和小Ho在吃过晚饭之后,来到了一个巨大的鬼屋!

鬼屋中一共有N个地点,分别编号为1..N,这N个地点之间互相有一些道路连通,两个地点之间可能有多条道路连通,但是并不存在一条两端都是同一个地点的道路。

不过这个鬼屋虽然很大,但是其中的道路并不算多,所以小Hi还是希望能够知道从入口到出口的最短距离是多少?

输入

每个测试点(输入文件)有且仅有一组测试数据。

在一组测试数据中:

第1行为4个整数N、M、S、T,分别表示鬼屋中地点的个数和道路的条数,入口(也是一个地点)的编号,出口(同样也是一个地点)的编号。

接下来的M行,每行描述一条道路:其中的第i行为三个整数u_i, v_i, length_i,表明在编号为u_i的地点和编号为v_i的地点之间有一条长度为length_i的道路。

对于100%的数据,满足N<=10^5,M<=10^6, 1 <= length_i <= 10^3, 1 <= S, T <= N, 且S不等于T。

对于100%的数据,满足小Hi和小Ho总是有办法从入口通过地图上标注出来的道路到达出口。

输出

对于每组测试数据,输出一个整数Ans,表示那么小Hi和小Ho为了走出鬼屋至少要走的路程。

Sample Input

5 10 3 5
1 2 997
2 3 505
3 4 118
4 5 54
3 5 480
3 4 796
5 2 794
2 5 146
5 4 604
2 5 63

Sample Output

172

真SPFA。。。。

#include<iostream>
#include<cstring>
#include<cstdio>
#include<vector>
#include<queue>

using namespace std;
#define mp(x, y) make_pair(x, y)
typedef pair<int, int> Pr;
const int N = 100000 + 5;
const int INF = 0x3f3f3f3f;
int n, m, s, t, dist[N];
bool in[N];
vector<Pr> v[N];
queue<int> Q;
int SPFA(){
    for(int i = 1; i <= n; i++) dist[i] = INF, in[i] = false;
    dist[s] = 0;
    in[s] = true;
    Q.push(s);
    while(!Q.empty()){
        int u = Q.front(); Q.pop();
        in[u] = false;
        for(int i = v[u].size() - 1; i >= 0; i--){
            int j = v[u][i].first;
            if(dist[j] > dist[u] + v[u][i].second){
                dist[j] = dist[u] + v[u][i].second;
                if(!in[j]){
                    Q.push(j);
                    in[j] = true;
                }
            }
        }
    }
    return dist[t];
}
void Input_data(){
    int x, y, c;
    for(int i = 1; i <= m; i++){
        scanf("%d %d %d", &x, &y, &c);
        v[x].push_back(mp(y, c));
        v[y].push_back(mp(x, c));
    }
}
int main(){
    scanf("%d %d %d %d", &n, &m, &s, &t);
    Input_data();
    printf("%d
", SPFA());
}
 




原文地址:https://www.cnblogs.com/Pretty9/p/7384034.html