生活随笔
收集整理的這篇文章主要介紹了
单源最短路
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目描述
給一個 n(1 \leq n \leq 2500)n(1≤n≤2500) 個點 m(1 \leq m\leq 6200 )m(1≤m≤6200) 條邊的無向圖,求 ss 到 tt 的最短路。
輸入格式
第一行四個由空格隔開的整數 nn、mm、ss、tt。
之后的 mm 行,每行三個正整數 si,ti,wi.
輸出格式
一個整數表示從 ss 到 tt 的最短路長度。數據保證至少存在一條道路。
樣例
Inputcopy Outputcopy
7 11 5 4
2 4 2
1 4 3
7 2 2
3 4 3
5 7 5
7 3 3
6 1 1
6 3 4
2 4 3
5 6 3
7 2 1
7
#include<bits/stdc++.h>
using namespace std
;const int N
=2510;int g
[N
][N
],dist
[N
];
bool st
[N
];int n
,m
,s
,t
;void dijkstra(int s
)
{memset(dist
,0x3f,sizeof dist
);memset(st
,false,sizeof st
);dist
[s
]=0;for(int i
=0; i
<n
-1; i
++){int t
=-1;for(int j
=1; j
<=n
; j
++)if(!st
[j
]&&(t
==-1||dist
[t
]>dist
[j
]))t
=j
;st
[t
]=true;for(int j
=1; j
<=n
; j
++)dist
[j
]=min(dist
[j
],dist
[t
]+g
[t
][j
]);}
}int main()
{memset(g
,0x3f,sizeof g
);cin
>>n
>>m
>>s
>>t
;for(int i
=1; i
<=m
; i
++){int a
,b
,c
;cin
>>a
>>b
>>c
;g
[a
][b
]=min(g
[a
][b
],c
);g
[b
][a
]=min(g
[b
][a
],c
);}dijkstra(s
);cout
<<dist
[t
]<<'\n';return 0;
}
總結
以上是生活随笔為你收集整理的单源最短路的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。