链接:https://vjudge.net/problem/Aizu-0189#author=ksqsf
思路:通过三重循环以及dp数组,更新两点之间的最短距离。
代码:
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
int dp[50][50];
const int INF = 1e9;
int main(){
int a,b,n,m,dist;
while(cin>>m&&m!=0){
n = 0;
for(int i=0;i<=m;i++)
for(int j=0;j<=m;j++)
dp[i][j] = INF;
for(int i=0;i<m;i++){
dp[i][i] = 0;
cin>>a>>b>>dist;
dp[a][b] = dp[b][a] = dist;
n = max(n,max(a,b));
}
for(int j=0;j<=n;j++){
for(int k=0;k<=n;k++){
for(int p=0;p<=n;p++){
dp[k][p] = min(dp[k][p],dp[k][j]+dp[j][p]);//一定记得前面是内部两重循环对应的下标,,否则死不瞑目!!!!
}
}
}
int sum = 1e9;
int ans = 0;
for(int i=0;i<=n;i++){
int temp = 0;
for(int j=0;j<=n;j++){
temp+=dp[i][j];
}
if(temp<sum){
sum = temp;
ans = i;
}
}
cout<<ans<<" "<<sum<<endl;
}
return 0;
}