【POJ 3268 --- Silver Cow Party】dijsktra,最短路

【POJ 3268 --- Silver Cow Party】dijkstra,最短路

题目来源:点击进入【POJ 3268 — Silver Cow Party】

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.

解题思路

根据题意我们知道求从目的地回去很容易得到。只需要使用dijkstra模板就能求出来。
关键是如何求从某点到目的地,当然我们可以求每个点到目的地的距离。但是这样显得较为麻烦。
我们只需将cost[i][j]与cost[j][i]交换。那么之前表示从i到j的距离就变成了从j到i的距离。
那么我们将交换后的cost数组求一次dijkstra得到的dis数组表示的就不是之前的从x到某地的距离了,而是从某地到x的距离。

这样我们就分别求出来从某地到x的距离,以及x到某的的距离。然后我们只需将其分别加起来找最大值即可。

AC代码:

#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
#define SIS std::ios::sync_with_stdio(false),cin.tie(0),cout.tie(0)
#define endl '\n'
const int MAXN = 1005;
const int inf = 0x3f3f3f3f;
int cost[MAXN][MAXN],dis[MAXN],chage[MAXN];
bool vis[MAXN];
int n,m,x;

void dijkstra()
{
    memset(dis,inf,sizeof(dis));
    memset(vis,false,sizeof(vis));
    dis[x]=0;
    while(true)
    {
        int v=-1;
        for(int i=1;i<=n;i++)
            if(!vis[i] && (v==-1 || dis[i]<dis[v])) v=i;
        if(v==-1) break;
        vis[v]=true;
        for(int i=1;i<=n;i++)
            dis[i]=min(dis[i],dis[v]+cost[v][i]);
    }
}

int main()
{
    SIS;
    int u,v,val;
    memset(cost,inf,sizeof(cost));
    cin >> n >> m >> x;
    while(m--)
    {
        cin >> u >> v >> val;
        cost[u][v]=val;
    }
    dijkstra();
    for(int i=1;i<=n;i++) chage[i]=dis[i];
    for(int i=1;i<=n;i++)
        for(int j=1;j<=i;j++)
            swap(cost[i][j],cost[j][i]);
    dijkstra();
    int ans=0;
    for(int i=1;i<=n;i++)
        ans=max(ans,dis[i]+chage[i]);
    cout << ans << endl;
    return 0;
}
发布了412 篇原创文章 · 获赞 135 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/qq_41879343/article/details/104083271