题目
07:Shortest Path
 总时间限制: 1000ms 内存限制: 65536kB
 描述
 There is a graph with N nodes. Given the length of each edge between the nodes. Find the shortest path from S to E.
输入
 First line: three positive integer number N (N <= 100), S (S <= N), E(E <= N).
 Next N lines: the i-th line contains N non-negative integers (<= 100), indicating the length of edge from the i-th node to any nodes.
 输出
 One line contains several integers, indicating the indexes of node in the shortest path from S to E.
 样例输入
 4 1 4
 0 3 6 8
 3 0 2 9
 6 2 0 2
 8 9 2 0
 样例输出
 1 2 3 4
翻译
描述
 有一个有N个节点的图。给定节点之间每条边的长度。找到从S到E的最短路径。
 输入
 第一行:三个正整数N(N<=100)、S(S<=N)、E(E<=N)。
 接下来的N行:第i行包含N个非负整数(<=100),表示从第i个节点到任何节点的边的长度。
 输出
 一行包含几个整数,表示从S到E的最短路径中节点的索引。
代码
#include <bits/stdc++.h>
 using namespace std;
 const int N=201;
 struct node{
 int x,//到达该点的最短路程
 pre;//到该该点最短路径的上一点
 }f[101]; //到达该位置时最短路径
 int n,
 s,
 e,
 d[101][101];//两点间距离
 void go(int x){//从该点出发更新到达另一点的最短距离
 for(int i=1;i<=n;i++){//遍历所有点
 if(x!=i&&f[i].x>f[x].x+d[x][i]){//出发点的最短距离+两点间距离如果小于到达点的最短距离
 f[i].x=f[x].x+d[x][i];//更新最短路径
 f[i].pre=x;
 go(i);//继续找路
 }
 }
 }
 /*
 从已知最短距离的点出发,遍历非出发点的所有点
 如果到达距离更短就用,
 f[s2]=f[s1]+d[s1][s2]
 从已到达点,也可以到周边所有点,有可能有比最短点还短的
 */
 int main(){
 //freopen(“data.cpp”,“r”,stdin);
 cin>>n>>s>>e;
 for(int i=1;i<=n;i++)
 for(int j=1;j<=n;j++)cin>>d[i][j];
 for(int i=1;i<=n;i++)f[i].x=numeric_limits::max();
 f[s].x=0;f[s].pre=0;
 go(s);
 //for(int i=1;i<=n;i++)cout<<i<<“\t”;cout<<endl;
 //for(int i=1;i<=n;i++)cout<<f[i].pre<<“\t”;cout<<endl;
 //for(int i=1;i<=n;i++)cout<<f[i].x<<“\t”;cout<<endl;
 int x=e;
 stack s;
 while(x){
 s.push(x);x=f[x].pre;
 }
 while(!s.empty()){
 cout<<s.top()<<" ";s.pop();
 }
 return 0;
 }
小结
ac了,但怎么感觉有点沉重,是不是这个判断有误!
 最短路径。