in.txt:
6
00 20 50 30 00 00
20 00 25 00 00 70
50 25 00 40 25 50
30 00 40 00 55 00
00 00 25 55 00 10
00 70 50 00 10 00
out.txt:
-1 20 45 30 70 80
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
const int Max = 1000;
int n; //节点数
int dist[100];
bool state[100];
int data[100][100];
int findMin()
{
int min = Max;
int minNode = 0;
for(int i=1;i<=n;i++)
{
if((dist[i]<min)&&(!state[i]))
{
min = dist[i];
minNode = i;
}
}
return minNode;
}
int main()
{
ifstream in("d:/in.txt"); //以输入方式打开文件
ofstream out("d:/out.txt"); //以输出方式打开文件
memset(state, 0, sizeof(state));
in>>n;
for(int i=1;i<=n;i++) //初始化
{
for(int j=1;j<=n;j++)
{
in >> data[i][j];
if(data[i][j]==0)
{
data[i][j]=Max;
}
}
}
for(int k=1;k<=n;k++)
{
dist[k]=data[1][k];
}
state[1]=true;
int num = 1;
while( num<n )
{
int node = findMin();
if(node!=0)
{
num++;
state[node] = true;
for(int i=1;i<=n;i++)
{
if(dist[i]>dist[node]+data[node][i]&&(!state[i]))
{
dist[i]=dist[node]+data[node][i];
}
}
}else{
break;
}
}
for(int m=1;m<=n;m++)
{
if(dist[m] == Max)
{
out<<-1;
}else{
out<<dist[m];
}
if(m==n)
{
out<<endl;
}else{
out<<" ";
}
}
in.close();
out.close();
return 0;
}