Silver Cow Party POJ - 3268(dijkstra+反向交换)
題意:
求X到某點來回路程的最短路的最大值。
模板更新中。。。
題目
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到某點的最短路可以由dijkstra算法求得,但是某點回來的路程需要對每個點都使用dijkstra算法,時間復雜度過大。
逆向思維:返程為往程的逆過程。
此時,只需要使用兩次dijkstra算法就可以了。
AC代碼
#include<stdio.h> #include<string.h> #include<algorithm> using namespace std; const int inf=0x3f3f3f3f; const int M=1e3+10; int m,n,k,ans; int dp[M][M],dis[M],s[M],book[M]; void dijkstra() {memset(book,0,sizeof(book));for(int i=1; i<=n; i++)dis[i]=dp[k][i];dis[k]=0;for(int i=1; i<n; i++){int ans=inf,kk;for(int j=1; j<=n; j++)if(!book[j]&&ans>dis[j]){ans=dis[j];kk=j;}book[kk]=1;for(int j=1; j<=n; j++)dis[j]=min(dis[j],dis[kk]+dp[kk][j]);} } int main() {scanf("%d%d%d",&n,&m,&k);memset(dp,inf,sizeof(dp));for(int i=1; i<=n; i++)dp[i][i]=0;for(int i=1; i<=m; i++){int t1,t2,t3;scanf("%d%d%d",&t1,&t2,&t3);if(dp[t1][t2]>t3)dp[t1][t2]=t3;}dijkstra();for(int i=1; i<=n; i++)s[i]=dis[i];for(int i=1; i<=n; i++)for(int j=i+1; j<=n; j++)swap(dp[i][j],dp[j][i]);dijkstra();for(int i=1; i<=n; i++)ans=max(ans,s[i]+dis[i]);printf("%d\n",ans);return 0; }總結
以上是生活随笔為你收集整理的Silver Cow Party POJ - 3268(dijkstra+反向交换)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 批量删除文件名称的一部分根据文件名批量删
- 下一篇: 电脑总是弹出FF新推荐电脑弹窗ff新推荐