POJ3268 最短路

来源:互联网 发布:淘宝网婴儿布鞋 编辑:程序博客网 时间:2024/06/09 22:37

题目链接:http://poj.org/problem?id=3268
题意:奶牛派对:有分别来自 N 个农场的 N 头牛去农场 X 开party,农场间由 M 条有向路径连接。每头牛一来一回都挑最短的路走,求它们走的路的最大长度?
规模:1 ≤ N ≤ 1000,1 ≤ M ≤ 100,000,1 ≤ Ti ≤ 100(路径长度)
类型:最短路
分析:
乍一看是一个Floyd-Warshall算法,很开心得敲完交上去,是个TLE,还是低估了N^3的复杂度啊。
其实这道题可以用一种特别的方法建图,简单求解。核心思想如下:
根据边建立两个图,一是正常的建图方式,我们可以用dijkstra求出回去的最短路(以X作为源点的单源最短路);二是进行反向建边,即本来的边{a–>b, cost c} 建图为{b–>a ,cost c},再以X作为源点求单源最短路,这就是“来”的最短路。最后两个相加。
时间复杂度&&优化:
代码:

#include<stdio.h>#include<string.h>#include<stdlib.h>#include<queue>#include<stack>#include<math.h>#include<vector>#include<algorithm>#include<iostream>using namespace std;const int MAX_N = 1005;const int MAX_M = 100005;const int inf = 1000000007;const int mod = 1000000007;int n,m,x;int a1[MAX_N][MAX_N];int a2[MAX_N][MAX_N];struct edge{    int to,cost;};typedef pair<int,int> P;///first是最短距离,second是顶点的编号int V;vector<edge> G1[MAX_N];vector<edge> G2[MAX_N];int d1[MAX_N];int d2[MAX_N];void Dijkstra(int s,vector<edge> G[],int *d){        priority_queue<P,vector<P>,greater<P> >que;        for(int i=0;i<n;i++){            d[i]=inf;        }        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));                }            }        }//        for(int i=0;i<n;i++){//            cout<<d[i]<<" ";//        }cout<<endl;}int main(){    while(cin>>n>>m>>x&&n&&m&&x){        x--;        for(int i=0;i<m;i++){            int a,b,c;            cin>>a>>b>>c;            a--;b--;            edge tmp;            tmp.to=b;tmp.cost=c;            G1[a].push_back(tmp);            tmp.to=a;tmp.cost=c;            G2[b].push_back(tmp);        }        Dijkstra(x,G1,d1);        Dijkstra(x,G2,d2);        int maxx=0;        for(int i=0;i<n;i++){            //cout<<d1[i]<<" "<<d2[i]<<endl;            if(i!=x)maxx=max(maxx,d1[i]+d2[i]);        }        cout<<maxx<<endl;    }    return 0;}
0 0
原创粉丝点击