奶牛派对:有分别来自 N 个农场的 N 头牛去农场 X 嗨皮,农场间由 M 条有向路径连接。每头牛来回都挑最短的路走,求它们走的路的最大长度?
思路:
如果不用优先队列的话,Dijsktra的效率为O(2|E|+|v|^2),用优先队列查找里源点最近的点时效率为O(log|V|),整体效率为O(2|E|+|v|log|V|)
#include <limits.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <algorithm>
#include <iostream>
#include <iterator>
#include <sstream>
#include <queue>
#include <stack>
#include <string>
#include <vector>
#include <set>
#include <map>
//#define ONLINE_JUDGE
#define eps 1e-6
#define INF 0x7fffffff //INT_MAX
#define inf 0x3f3f3f3f //int??????????????????
#define FOR(i,a) for((i)=0;i<(a);(i)++) //[i,a);
#define MEM(a) (memset((a),0,sizeof(a)))
#define sfs(a) scanf("%s",a)
#define sf(a) scanf("%d",&a)
#define sfI(a) scanf("%I64d",&a)
#define pf(a) printf("%d\n",a)
#define pfI(a) printf("%I64d\n",a)
#define pfs(a) printf("%s\n",a)
#define sfd(a,b) scanf("%d%d",&a,&b)
#define sft(a,b,c)scanf("%d%d%d",&a,&b,&c)
#define for1(i,a,b) for(int i=(a);i<b;i++)
#define for2(i,a,b) for(int i=(a);i<=b;i++)
#define for3(i,a,b)for(int i=(b);i>=a;i--)
#define MEM1(a) memset(a,0,sizeof(a))
#define MEM2(a) memset(a,-1,sizeof(a))
#define MEM3(a) memset(a,0x3f,sizeof(a))
#define MEMS(a) memset(a,'\0',sizeof(a))
#define LL __int64
const double PI = acos(-1.0);
template<class T> T gcd(T a, T b) { return b ? gcd(b, a % b) : a; }
template<class T> T lcm(T a, T b) { return a / gcd(a, b) * b; }
template<class T> inline T Min(T a, T b) { return a < b ? a : b; }
template<class T> inline T Max(T a, T b) { return a > b ? a : b; }
using namespace std;
template<class T>
T Mint(T a, T b, T c) {
if (a>b) {
if (c>b)
return b;
return c;
}
if (c>a)
return a;
return c;
}
template<class T>
T Maxt(T a, T b, T c) {
if (a>b) {
if (c>a)
return c;
return a;
}
else if (c > b)
return c;
return b;
}
const int maxn=1000;
int T,n,m,x;
struct edge{
int to,cost;
edge(){}
edge(int to,int cost):to(to),cost(cost){}
};
typedef pair<int,int> P;
vector<edge> G[maxn];
int dis[maxn][maxn];//dis[i][j]表示i->j的距离
int a,b,c;
void Dijsktra(int s){
priority_queue<P, vector<P>, greater<P> > q;//优先队列优化,维护最短路径
MEM3(dis[s]);
dis[s][s]=0;;
q.push(P(0,s));
while(!q.empty()){
P p=q.top();q.pop();
int v=p.second;
if(dis[s][v]<p.first) continue;
for(int i=0;i<G[v].size();i++){//更新最短路径
edge e=G[v][i];
if(dis[s][e.to]>dis[s][v]+e.cost){
dis[s][e.to]=dis[s][v]+e.cost;
q.push(P(dis[s][e.to],e.to));
}
}
}
}
int main(){
#ifndef ONLINE_JUDGE
freopen("test.in","r",stdin);
freopen("test.out","w",stdout);
#endif
while(~sft(n,m,x)){
x--;
for1(i,0,m){
sft(a,b,c);
a--,b--;
G[a].push_back(edge(b,c));
//G[b].push_back(edge(a,c));
}
for1(i,0,n) Dijsktra(i);//更新i点到其他所有点的最短路径
int ans=0;
for1(i,0,n){//更新最大距离
if(i==x) continue;
ans=max(ans,dis[i][x]+dis[x][i]);
}
pf(ans);
}
return 0;
}