Silver Cow Party (POJ - 3268 )
Silver Cow Party (POJ - 3268 )
這道題是我做的最短路專題里的一道題,但我還沒做這個,結果比賽就出了,真是。。。。。。。。。。
題目:
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 3Sample Output
10Hint
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.
題目翻譯:
N個農場(1≤N≤1000)各1頭奶牛,方便編號1。N將參加在農場#X(1≤X≤N)舉行的大型奶牛聚會,共計M(1≤M≤100,000)個單向(單行道連接成對農場;i路要求Ti(1≤Ti≤100)時間單位穿越。
每頭牛都必須步行去參加聚會,聚會結束后,再回到她的農場。每頭牛都很懶,因此會選擇最短時間內的最佳路線。牛的回程路線可能與它原來去派對的路線不同,因為路是單向的。
在所有的牛中,一頭牛走著去參加聚會,然后又走回來所需要的時間最長是多少?
輸入
第1行:三個空格分隔的整數,分別是:N、M和X
行2 . .M+1:第i+1行用三個空格分隔的整數描述了i路:Ai、Bi和Ti。描述的道路從人工智能農場到人工智能農場,需要穿越Ti時間單位。
輸出
第1行:一個整數:任何一頭牛必須行走的最長時間。
樣例輸入
4 8 2
1 2 4
1 2 3
1 4 7
2 1 1
2 3 5
3 1 2
3 4 4
4 2 3
樣例輸出
10
提示
奶牛4直接進入隊伍(3個單位),通過農場1和農場3(7個單位)返回,共10次。
思路:借鑒一下大佬的思路,每頭牛返回的最短時間很簡單就可以算出來,這相當于從目標牛為起點求單源最短路徑。但每頭牛出發到目標牛的最短時間無法直接算出來,稍微轉換一下,發現這個最短時間其實可以通過把所有的邊取反向,然后再從目標牛求一次單源最短路徑得到。得到這兩個最短路徑之后,取它們的和的最大者即可。
AC代碼:
#include <stdio.h> #include <string.h> #include <algorithm> #include <iostream> #include <math.h> #define inf 0x3f3f3f3f #define maxn 1010 using namespace std; int dp[maxn][maxn]; int dis[maxn],vis[maxn]; int n,m,start,end; void dj() {memset(vis,0,sizeof(vis));for(int i=1; i<=n; i++){dis[i]=dp[start][i];}dis[start]=0;vis[start]=1;for(int i=1; i<=n; i++){int k=0,minn=inf;for(int j=1; j<=n; j++){if(vis[j]==0 && minn>dis[j]){minn=dis[j];k=j;}}vis[k]=1;for(int j=1; j<=n; j++){if(dis[j]>dis[k]+dp[k][j]){dis[j]=dis[k]+dp[k][j];}}} } void change() {for(int i=1; i<=n; i++)for(int j=1; j<=i; j++){swap(dp[i][j],dp[j][i]);} } int main() {scanf("%d%d%d",&n,&m,&start);int a[maxn];memset(dp,inf,sizeof(dp));while(m--){int u,v,w;scanf("%d%d%d",&u,&v,&w);dp[u][v]=w;}dj();for(int i=1; i<=n; i++){a[i]=dis[i];}change();dj();int num=0;for(int i=1; i<=n; i++){a[i]+=dis[i];num=max(num,a[i]);}printf("%d\n",num);return 0; }?
總結
以上是生活随笔為你收集整理的Silver Cow Party (POJ - 3268 )的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 56岁梁实第27次参加高考:希望是最后一
- 下一篇: 把文件夹中的文件名快速导出到excel表