AOJ 2249 Road Construction 最短路径 Dijkstra算法优化

#include 
#include 
#include 
using namespace std;
struct Edge
{
    int to, len, cost;
    Edge(int to = 0, int len = 0, int cost = 0) : to(to), len(len), cost(cost) {}
};
typedef pair P;
vector edges[10007];
int inf = 0x3f3f3f3f, N, M, d[10007], ans[10007];
bool used[10007];
void input()
{
    int from, to, len, cost;
    for (int i = 1; i <= M; i++)
    {
        scanf("%d%d%d%d", &from, &to, &len, &cost);
        edges[from].push_back(Edge(to, len, cost));
        edges[to].push_back(Edge(from, len, cost));
    }
}
void dijkstra()
{
    for (int i = 1; i <= N; i++)
    {
        d[i] = inf;
        used[i] = false;
        ans[i] = inf;
    }
    d[1] = 0;
    ans[1] = 0;
    priority_queue, greater

> que; que.push(P(0, 1)); while (!que.empty()) { P current = que.top(); que.pop(); if (used[current.second] || current.first > d[current.second]) { continue; } used[current.second] = true; for (int i = 0; i < edges[current.second].size(); i++) { Edge toEdge = edges[current.second][i]; if (d[current.second] + toEdge.len < d[toEdge.to]) { d[toEdge.to] = d[current.second] + toEdge.len; ans[toEdge.to] = toEdge.cost; que.push(P(d[toEdge.to], toEdge.to)); } if (d[current.second] + toEdge.len == d[toEdge.to] && toEdge.cost < ans[toEdge.to]) { ans[toEdge.to] = toEdge.cost; } } } } void solve() { dijkstra(); int res = 0; for (int i = 1; i <= N; i++) { res += ans[i]; } printf("%d\n", res); } void clearAll() { for (int i = 1; i <= N; i++) { edges[i].clear(); } } int main() { while (true) { scanf("%d%d", &N, &M); if (N == 0 && M == 0) { break; } input(); solve(); clearAll(); } return 0; }

你可能感兴趣的:(图论,算法,数据结构)