码迷,mamicode.com
首页 > 其他好文 > 详细

POJ3255(次短路)

时间:2015-03-27 22:16:20      阅读:129      评论:0      收藏:0      [点我收藏+]

标签:次短路

题目链接:点击打开链接


解题思路:

按照Dijkstra思想做的次短路,第一次用邻接表,注意题中是双向边并且节点的下标要分别-1.


完整代码:

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <set>
#include <vector>
#include <climits>
#include <queue>
using namespace std;
typedef long long LL;
const int maxn = 100001;

typedef pair<int , int> P;

struct edge
{
    int to , cost;
};

int INF = 99999999;
int n , r;
vector<edge> g[maxn];
int dist[maxn];
int dist2[maxn];

void solve()
{
    priority_queue< P , vector<P> , greater<P> > que;
    fill(dist , dist + n , INF);
    fill(dist2 , dist2 + n , INF);
    dist[0] = 0;
    que.push(P(0 , 0));
    while(!que.empty())
    {
        P p = que.top();
        que.pop();
        int v = p.second , d = p.first;
        if(dist2[v] < d)
        {
            continue;
        }
        for(int i = 0 ; i < g[v].size() ; i ++)
        {
            edge &e = g[v][i];
            int d2 = d + e.cost;
            if(dist[e.to] > d2)
            {
                swap(dist[e.to] , d2);
                que.push(P(dist[e.to] , e.to));
            }
            if(dist2[e.to] > d2 && dist[e.to] < d2)
            {
                dist2[e.to] = d2;
                que.push(P(dist2[e.to] , e.to));
            }
        }
    }
    cout << dist2[n-1] << endl;
}


int main()
{

    #ifdef DoubleQ
    freopen("in.txt" , "r" , stdin);
    #endif
    while(cin >> n >> r)
    {
        int a , b , d;
        for(int i = 0 ; i < r ; i ++)
        {
            cin >> a >> b >> d;
            a --;
            b --;
            struct edge temp;
            temp.to = b;
            temp.cost = d;
            g[a].push_back(temp);

            struct edge temp2;
            temp2.to = a;
            temp2.cost = d;
            g[b].push_back(temp2);
        }

        solve();
    }
    return 0;
}

更多精彩请访问:点击打开链接

POJ3255(次短路)

标签:次短路

原文地址:http://blog.csdn.net/u013447865/article/details/44682255

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!