poj3268 spfa

 

 

如題:http://poj.org/problem?id=3268

Silver Cow Party
Time Limit: 2000MS   Memory Limit: 65536K
Total Submissions: 15396   Accepted: 6966

Description

One cow from each of N farms (1 ≤ N ≤ 1000) conveniently numbered 1..N is going to attend the big cow party to be held at farm #X (1 ≤ XN). A total of M (1 ≤ M ≤ 100,000) unidirectional (one-way roads connects pairs of farms; road i requires Ti (1 ≤ Ti ≤ 100) units of time to traverse.

Each cow must walk to the party and, when the party is over, return to her farm. Each cow is lazy and thus picks an optimal route with the shortest time. A cow's return route might be different from her original route to the party since roads are one-way.

Of all the cows, what is the longest amount of time a cow must spend walking to the party and back?

Input

Line 1: Three space-separated integers, respectively: N, M, and X
Lines 2..M+1: Line i+1 describes road i with three space-separated integers: Ai, Bi, and Ti. The described road runs from farm Ai to farm Bi, requiring Ti time units to traverse.

Output

Line 1: One integer: the maximum of time any one cow must walk.

Sample Input

4 8 2
1 2 4
1 3 2
1 4 7
2 1 1
2 3 5
3 1 2
3 4 4
4 2 3

Sample Output

10

Hint

Cow 4 proceeds directly to the party (3 units) and returns via farms 1 and 3 (7 units), for a total of 10 time units.

Source

 

 

 

 

思路:給了目標點,首先從目標點求一次到其他點的最短路,再反向求一次,求最大和。

 

#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
#include<vector>
using namespace std;
#define MAXN 1005
typedef pair<int,int>P;
#define inf 0x0fffffff
#define max(a,b)(a>b?a:b)

struct edge
{
 int to,cost;
 edge(int a,int b):to(a),cost(b){}
};
vector<edge>G1[MAXN];
vector<edge>G2[MAXN];
int dis1[MAXN];
int dis2[MAXN];

void spfa(vector<edge>G[MAXN],int d[MAXN],int s,int n)
{
 priority_queue<P,vector<P>,greater<P> >que;
 int i;
 for(i=1;i<=n;i++)
  d[i]=inf;
 d[s]=0;
 que.push(P(0,s));
 while(!que.empty())
 {
  P p=que.top();
  que.pop();
  int u=p.second;
  if(d[u]<p.first)
   continue;
  for(i=0;i<G[u].size();i++)
  {
   edge e=G[u][i];
   if(d[e.to]>d[u]+e.cost)
   {
    d[e.to]=d[u]+e.cost;
    que.push(P(d[e.to],e.to));
   }
  }
 }
}
int main()
{
// freopen("C:\\Users\\Administrator\\Desktop\\1\\sparty.9.in","r",stdin); 
 int N,M,X;
 cin>>N>>M>>X;
 int i;
 for(i=0;i<M;i++)
 {
  int u,v,w;
  scanf("%d%d%d",&u,&v,&w);
  G1[u].push_back(edge(v,w));
  G2[v].push_back(edge(u,w));
 }
 spfa(G1,dis1,X,N);
 spfa(G2,dis2,X,N);
 int res=0;
 for(i=1;i<=N;i++)
 {
  if(dis1[i]!=inf&&dis2[i]!=inf)
  {
   res=max(res,dis1[i]+dis2[i]);
  }
 }
 cout<<res<<endl;
 return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章