POJ 2387

入门级的最短路。这里为了学习我使用了带有 min-priority queue的方法将时间复杂度优化至 O(E+VlogV)

#include <cstdio>
#include <vector>
#include <queue>
#include <set>
using namespace std;

const int INTMAX = 1000000;

struct Edge{
    int to;
    int length;
};

int T,N;
vector< vector<Edge> > graph(1005);
vector<Edge>::iterator it;
Edge source;


void Dijkstra(){
    vector<int> min_dis(graph.size(), INTMAX);
    min_dis[N]=0;
    set< pair<int, int> > active_vertices;
    active_vertices.insert( {0, N} );

    while (!active_vertices.empty()) {
        int where = active_vertices.begin()->second;

        if (where == 1) {printf("%d\n",min_dis[where]);return ;}

        active_vertices.erase( active_vertices.begin() );

        for(it=graph[where].begin();it!=graph[where].end();it++)
            if(min_dis[(*it).to] > min_dis[where]+(*it).length){
                active_vertices.erase( { min_dis[(*it).to], (*it).to} );
                min_dis[(*it).to] = min_dis[where]+(*it).length;
                active_vertices.insert({min_dis[(*it).to], (*it).to});
            }
    }
    return;
}

int main(){
    //freopen("cin", "r", stdin);
    scanf("%d %d",&T,&N);

    for(int i=0;i<T;i++){
        int a,b,c;

        Edge edge;
        scanf("%d %d %d",&a,&b,&c);
        edge.to=b;edge.length=c;
        graph[a].push_back(edge);
        edge.to=a;edge.length=c;
        graph[b].push_back(edge);
    }

    Dijkstra();

    return 0;
}
点赞