1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
| #include<iostream> #include<vector> using namespace std; const int &INF=100000000; void floyd(vector<vector<int> > &distmap, vector<vector<int> > &path)
{ const int &NODE=distmap.size(); path.assign(NODE,vector<int>(NODE,-1)); for(int k=1; k!=NODE; ++k) for(int i=0; i!=NODE; ++i) for(int j=0; j!=NODE; ++j) if(distmap[i][j]>distmap[i][k]+distmap[k][j]) { distmap[i][j]=distmap[i][k]+distmap[k][j]; path[i][j]=k; } } void print(const int &beg,const int &end, const vector<vector<int> > &path) { if(path[beg][end]>=0) { print(beg,path[beg][end],path); print(path[beg][end],end,path); } else cout<<"->"<<end; } int main() { int n_num,e_num,beg,end; cout<<"(不处理负权回路)输入点数、边数:"; cin>>n_num>>e_num; vector<vector<int> > path, distmap(n_num,vector<int>(n_num,INF)); for(int i=0,p,q; i!=e_num; ++i) { cout<<"输入第"<<i+1<<"条边的起点、终点、长度(100000000代表无穷大,不联通):"; cin>>p>>q; cin>>distmap[p][q]; } floyd(distmap,path); cout<<"计算完毕,可以开始查询,请输入出发点和终点:"; cin>>beg>>end; cout<<"最短距离为"<<distmap[beg][end]<<",打印路径:"<<beg; print(beg,end,path); }
|