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 ≤ X ≤ N). 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.
题意:
在X地开party,其他地方的cow要去X地参加,从每个地方到X,然后再回来,每个路径要使时间最短,求解所有最小值的最大值。
题目解析:
思路一(TEL,但是这个是第一想法):
没什么可解释的,求解每两个点之间的最短路径,然后计算cost【x】【i】+cost【i】【x】的最大值。但是由于复杂度达到了n^3,所以会tel
这里就写一下floyd的核心代码吧,毕竟不能ac的代码
void floyd(){
for(int k=1;k<=n;k++){
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
cost[i][j]=min(cost[i][j],cost[i][k]+cost[k][j]);
}
}
}
}
思路2(两次dijkstra)
- 准备两个数组,第一个数组是原矩阵,第二个数组相当于转置矩阵。对于第一个数组,可以求解出X到其他地方的最小值;对于第二个数组,虽然也是求X‘到其他地方的最小值,但由于是路径都反向了,所有其实是其他地方到X地的最小值
- 求解dis1【x】+dis2【x】的最大值
奉上代码
#include<iostream>
#include<cstdio>
#include<string>
#include<limits.h>
#include<algorithm>
#include<cstring>
#include<math.h>
#include<set>
#include<vector>
#include<queue>
#include<set>
#include<stdlib.h>
#include<time.h>
using namespace std;
typedef long long ll;
#define inf 0x3f3f3f3f
typedef pair<int,int> P;
int n,m,x;
int cost1[1010][1010];
int cost2[1010][1010];
int dis1[1010];
int dis2[1010];
void init(){
fill_n(&cost1[0][0],1010*1010,inf);
fill_n(&cost2[0][0],1010*1010,inf);
fill_n(dis1,1010,inf);
dis1[x]=0;
fill_n (dis2,1010,inf);
dis2[x]=0;
for(int i=1;i<=n;i++){
cost1[i][i]=0;
cost2[i][i]=0;
}
}
void dijkstra(int cost[][1010],int dis[]){
priority_queue<P,vector<P>,greater<P> > myQ;
myQ.push(P(0,x));
while(!myQ.empty()){
P p=myQ.top();
myQ.pop();
if(p.first>dis[p.second]){
continue;
}
for(int i=1;i<=n;i++){
if(dis[i]>cost[p.second][i]+p.first){
dis[i]=cost[p.second][i]+p.first;
myQ.push(P(dis[i],i));
}
}
}
}
int solve(){
dijkstra(cost1,dis1);
dijkstra(cost2,dis2);
int sum=0;
for(int i=1;i<=n;i++){
int temp=dis1[i]+dis2[i];
sum=max(temp,sum);
}
return sum;
}
int main() {
while(scanf("%d%d%d",&n,&m,&x)!=EOF){
init();
int x,y,c;
while(m--){
scanf("%d%d%d",&x,&y,&c);
cost1[x][y]=c;
cost2[y][x]=c;
}
printf("%d\n",solve());
}
return 0;
}