Silver Cow Party

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: NM, 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,每一頭牛都要去參加聚會併到自己的農場,還有就是每一頭牛都很懶,所以它們走的都會是耗時最短的路,讓我們求耗時最長的牛總共花了多長時間。

第一行3個數字n、m、x,表示總共n頭牛、m條路線、聚會在x農場舉行,接下來m行分別是從A農場到B農場耗時t。注意這是單向的。

思路:2個dijkstra分別計算從i農場到x農場、從x農場回到i農場的最小耗時,然後選擇相加耗時最大的就好

代碼:

#include<stdio.h>
#include<string.h>
#define inf 0x3f3f3f
#include<algorithm>
using namespace std;
int n,m,x,a,b,t,ans=0,e[1200][1200],dis1[1200],dis2[1200],vis1[1200],vis2[1200];
int main()
{
    scanf("%d %d %d",&n,&m,&x);
    for(int i=1; i<=n; i++)
    {
        for(int j=1; j<=n; j++)
            e[i][j]=(i==j)?0:inf;
    }
    for(int i=0; i<m; i++)
    {
        scanf("%d %d %d",&a,&b,&t);
        e[a][b]=min(e[a][b],t);
    }
    for(int i=1;i<=n;i++)
    {
        dis1[i]=e[i][x];//dis1記錄的是從i農場到x農場的最小耗時
        dis2[i]=e[x][i];//dis2記錄的是從x農場回到i農場的最小耗時
    }
    for(int i=1;i<=n;i++)
    {
        int k1,k2,mi1=inf,mi2=inf;
        for(int j=1;j<=n;j++)
        {
            if(vis1[j]==0&&dis1[j]<mi1)
            {
                mi1=dis1[j];
                k1=j;
            }
            if(vis2[j]==0&&dis2[j]<mi2)
            {
                mi2=dis2[j];
                k2=j;
            }
        }
        vis1[k1]=1;
        vis2[k2]=1;
        for(int j=1;j<=n;j++)
        {
            dis1[j]=min(dis1[j],dis1[k1]+e[j][k1]);//最開始寫成dis1[k1]+e[k1][j],WA了一發,dis1[k1]+e[k1][j]的意思是k1→x+k1→j,而我們要的是j→k1+k1→x
            dis2[j]=min(dis2[j],dis2[k2]+e[k2][j]);
        }
    }
    for(int i=1; i<=n; i++)
        ans=max(ans,dis1[i]+dis2[i]);//我們要的是來回共耗時最大的一個~~~
    printf("%d\n",ans);
    return 0;
}

發佈了78 篇原創文章 · 獲贊 4 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章