暢通工程續Time Limit: 3000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 69930 Accepted Submission(s): 27049 Problem Description 某省自從實行了很多年的暢通工程計劃後,終於修建了很多路。不過路多了也不好,每次要從一個城鎮到另一個城鎮時,都有許多種道路方案可以選擇,而某些方案要比另一些方案行走的距離要短很多。這讓行人很困擾。
Input 本題目包含多組數據,請處理到文件結束。
Output 對於每組數據,請在一行裏輸出最短需要行走的距離。如果不存在從S到T的路線,就輸出-1.
Sample Input 3 3 0 1 1 0 2 3 1 2 1 0 2 3 1 0 1 1 1 2
Sample Output 2 -1 |
多源最短路;模板:
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
typedef long long ll;
const ll INF=1<<29;
ll d[2000][2000];
int main(){
int s,t,n,m;
while(cin>>n>>m){
int a,b,c;
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
if(i==j) d[i][j]=0;
else d[i][j]=INF;
}
}
while(m--){
cin>>a>>b>>c;
if(d[a][b]>c)
d[a][b]=d[b][a]=c;
}
cin>>s>>t;
for(int k=0;k<n;k++){
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
if(d[i][k]!=INF&&d[k][j]!=INF){
d[i][j]=min(d[i][j],d[i][k]+d[k][j]);
}
}
}
}
if(d[s][t]!=INF)
cout<<d[s][t]<<endl;
else cout<<-1<<endl;
}
return 0;
}