poj 3268 dijkstra


题目链接:点击打开链接

题意: 输入N(定点数) M(边数 单向边) X(目的地) , 求在所有顶点中 i到x的最短距离 与x到i 的最短距离和 的最大值。

思路:先用最短路算法求出D[i][x],再用同样的算法求出D[x][i] , 然后求和,找出最大值。

最开始二维用Floyd 去求 D[i][x] 和D[x][i] ,然后求结果,发现wrong answer 了, 后来发现是因为Floyd  不能处理 起始点和终点相同的边,最后输入的那条边会把前面的覆盖。

后来用邻接矩阵存图,dijkstra 求最短路。

#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <string.h>
#include <queue>
#include <vector>
using namespace std;
typedef pair<int , int> P ;
const int maxv = 1005,  INF = 1e9;
int n , d[maxv] , d1[maxv] ; //d[i]表示从 s出发到 i的最短距离, d1[i] 表示从i出发到 s的最短距离

struct edge{int to , cost ;};
vector<edge> G[maxv] ; //G[i]存储的是以i为起点的边
struct Edge{int from , cost ;};
vector<Edge> G1[maxv] ; //G1[i]存储的是以i为终点的边

int find_Max(int s)
{
    priority_queue<P , vector<P> , greater<P> > que ;
   // priority_queue<P , vector<P> ,greater<P> > que1 ;
    fill(d , d + n +1 , INF) ;
    fill(d1 , d1 + n + 1 , INF) ;
    d1[s] = 0 ;
    d[s] = 0 ; que.push(P(0 , s)) ;
    while(!que.empty())
    {
        P p = que.top() ; que.pop() ;
        int v = p.second ;
        if(d[v] < p.first ) continue ;
        for(int i = 0 ; i < G[v].size() ; i ++)
        {
            edge e = G[v][i] ;
            if(d[e.to] > d[v] + e.cost)
            {
                d[e.to] = d[v] + e.cost ;
                que.push(P(d[e.to] , e.to)) ;
            }
        }
    }

    que.push(P(0 , s)) ;
    while(!que.empty())
    {
        P p = que.top() ; que.pop() ;
        int v = p.second ;
        if(d1[v] < p.first) continue ;
        for(int i = 0 ; i < G1[v].size() ; i ++)
        {
            Edge e = G1[v][i] ;
            if(d1[e.from] > d1[v] + e.cost)
            {
               d1[e.from] = d1[v] + e.cost ;
               que.push(P(d1[e.from] , e.from)) ;
            }
        }
    }

    int Max = 0 ;
    for(int i = 1 ; i <= n ; i ++)
    {
        Max = max(Max , d[i] + d1[i]) ;
    }
    return Max ;
}

int main()
{
    //freopen("a.txt" , "r" , stdin ) ;
    int m , x , from , to , cost ;
    edge e ; Edge e1 ;
    while(scanf("%d%d%d" , &n , &m , &x) != EOF)
    {
       for(int i = 1 ; i <= n ; i ++) {G[i].clear() ; G1[i].clear() ;} //清空
       for(int i = 1 ; i <= m ; i ++)
       {
           scanf("%d%d%d" , &from , &to , &cost) ;
           e.to = to ; e.cost = cost ;
           e1.from = from , e1.cost = cost ;
           G[from].push_back(e) ;
           G1[to].push_back(e1) ;
       }

       printf("%d\n" , find_Max(x)) ;
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值