畅通工程续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;
}