62,614
社区成员
发帖
与我相关
我的任务
分享
#include<iostream>
#include<sstream>
#include<string>
#include<fstream>
using namespace std;
#define MAX 16
#define INFTY 1000
void DIJKSTRA(int A[][MAX],int d[],int p[],int s)
{
int index;
int i,j,u=INFTY,x,y,w;
d[s]=0;//原点到其他点的距离
int S[15],Q[15];
for(i=1;i<=15;i++)
{
d[i]=INFTY;
p[i]=-1;
S[i]=0;
}
S[0]=1;//存已经纳入的点
i=0;
for(w=0;w<=15;w++)//寻找距离最短的点
{
u=INFTY;
for(j=0;j<=15;j++)
{
if(A[i][j]!=INFTY)
if(d[j]>d[i]+A[i][j])
{
d[j]=d[i]+A[i][j];
p[j]=i;
}
}
for(x=1;x<=15;x++)
{
if(S[x]!=1)
if(u>d[x])
{
u=d[x];
y=x;
//cout<<u<<"d"<<endl;
}
}
S[y]=1;//把最短距离的点纳入进来
i=y;
}
}
void print(int p[],int end)
{
if(p[end] == 0)
{
cout << end<< "->";
return;
}
print(p,p[end]);
cout << end << "->";
}
int main()
{
int A[MAX][MAX];
int d[MAX],p[MAX];
int i,j,v;
string str;
for(i=0;i<=15;i++)
for(j=0;j<=15;j++)
A[i][j]=INFTY;
ifstream cin("4.txt");
while(getline(cin,str))
{
istringstream stream(str);
stream>>i>>j>>v;
A[i][j]=v;
}
//输入邻接矩阵结束
DIJKSTRA(A,d,p,0);
cout<<"0->";
print(p,15);
cout<<"15";
getchar();
getchar();
getchar();
}