CCF-20160904-交通规划

特殊Dijkstra求单源最短路径.

#include <iostream>
#include <cstdio>
#include <queue>
#include <vector>
#include <cstring>
using namespace std;
const int MAXN = 10005;
const int INF = 0x3fffff;
struct qnode{
    int v, c;
    qnode(int _v = 0, int _c = 0):v(_v), c(_c){}
    bool operator < (const qnode &r) const{
        return c > r.c;
    }
};

struct Edge{
    int v, cost;
    Edge(int _v = 0, int _cost = 0): v(_v), cost(_cost){}
};

vector<Edge> E[MAXN];
bool visit[MAXN];
int dist[MAXN];         //最短路
int COST[MAXN];         //存储单源结果

void Dijkstra(int start, int n)
{
    memset(visit, 0, sizeof(visit));
    for(int i = 1; i <= n; ++i)
    {
        dist[i] = INF;
        COST[i] = INF;
    } 
    priority_queue<qnode> que;
    while(!que.empty()) que.pop();
    COST[start] = 0;
    dist[start] = 0;
    que.push(qnode(start, 0));
    qnode tmp;

    while(!que.empty())
    {
        tmp = que.top();
        que.pop();

        int u = tmp.v;
        if(visit[u]) continue;
        visit[u] = true;

        for(int i = 0; i < E[u].size(); ++i)
        {
            int v = E[u][i].v;
            int cost = E[u][i].cost;

            if(!visit[v])
            {
                if(dist[v] > cost + dist[u])  //松弛操作
                {
                    COST[v] = cost;
                    dist[v] = dist[u] + cost;
                    que.push(qnode(v, dist[v]));
                }else if(dist[v] == cost + dist[u])
                    COST[v] = min(COST[v], cost);
            }

        }
    }
}

void addEdge(int u, int v, int w)   //无向图******
{
    E[u].push_back(Edge(v, w));
    E[v].push_back(Edge(u, w));
}

int main()
{
    int n, m;
    while(scanf("%d%d", &n, &m) != EOF)
    {
        int u, v, w;
        while(m--)
        {
            scanf("%d%d%d", &u, &v, &w);
            addEdge(u, v, w);
        }
        Dijkstra(1, n);
        int ans = 0;

        for(int i = 2; i <= n; ++i)
            ans += COST[i];
        printf("%d\n", ans);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值