poj 3268 dijkstra

来源:互联网 发布:淘宝网首页中年女装 编辑:程序博客网 时间:2024/05/19 03:25


题目链接:点击打开链接

题意: 输入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