对的代码
#include
#include
using namespace std;
const int maxN=1000;
const int maxInt=9999999;
int graph[maxN][maxN];
int cc[maxN];
int pre[maxN];
int n;
int path[maxN][maxN];
int main()
{
while(scanf("%d",&n)&&n!=0)
{
for(int i=1; i<=n; i++)
{
for(int j=1; j<=n; j++)
{
scanf("%d",&graph[i][j]);
if(graph[i][j]==-1)
graph[i][j]=maxInt;
path[i][j]=j;
}
}
for(int i=1; i<=n; i++)
scanf("%d",&cc[i]);
for(int k = 1; k <= n; k++)
{
for(int i = 1; i <= n; i++)
{
for(int j = 1; j <= n; j++)
{
if(i!=j&&j!=k&&i!=k)
{
int len = graph[i][k] + graph[k][j]+ cc[k];
if(graph[i][j] > len)
{
graph[i][j] = len;
path[i][j] = path[i][k];
}
else if(len == graph[i][j])
{
if(path[i][j] > path[i][k])
path[i][j] = path[i][k];
}
}
}
}
}
int a,b;
while(scanf("%d%d",&a,&b))
{
if(a==-1&&b==-1)
break;
printf("From %d to %d :\n",a,b);
printf("Path: %d", a);
int k = a;
while(k != b)
{
printf("-->%d", path[k][b]);
k = path[k][b];
}
printf("\n");
printf("Total cost : %d\n\n", graph[a][b]);
}
}
return 0;
}
#include
#include
using namespace std;
const int maxN=1000;
const int maxInt=9999999;
int graph[maxN][maxN];
int cc[maxN];
int pre[maxN];
int n;
int path[maxN][maxN];
int main()
{
while(scanf("%d",&n)&&n!=0)
{
for(int i=1; i<=n; i++)
{
for(int j=1; j<=n; j++)
{
scanf("%d",&graph[i][j]);
if(graph[i][j]==-1)
graph[i][j]=maxInt;
path[i][j]=j;
}
}
for(int i=1; i<=n; i++)
{
scanf("%d",&cc[i]);
for(int j=1; j<=n; j++)
{
if(graph[j][i]!=0)
{
graph[j][i]+=cc[i];
}
}
}
for(int k = 1; k <= n; k++)
{
for(int i = 1; i <= n; i++)
{
for(int j = 1; j <= n; j++)
{
if(i!=j&&j!=k&&i!=k)
{
int len = graph[i][k] + graph[k][j];//+ cc[k];
if(graph[i][j] > len)
{
graph[i][j] = len;
path[i][j] = path[i][k];
}
else if(len == graph[i][j])
{
if(path[i][j] > path[i][k])
path[i][j] = path[i][k];
}
}
}
}
}
int a,b;
while(scanf("%d%d",&a,&b))
{
if(a==-1&&b==-1)
break;
printf("From %d to %d :\n",a,b);
printf("Path: %d", a);
int k = a;
while(k != b)
{
printf("-->%d", path[k][b]);
k = path[k][b];
}
printf("\n");
printf("Total cost : %d\n\n", graph[a][b]-cc[b]);
}
}
return 0;
}