题目
过暑假了,阿杜准备出行旅游,他已经查到了某些城市的两两之间的距离及可行路线(可行路线有方向),如下图所示。请你编程计算从阿杜所住城市到其它城市的最短路径以帮助阿杜制定旅行计划。
【输入格式】
输入由若干行组成,第一行有三个整数,n(1≤n≤100)、m(1≤m≤n2)v(1≤m≤n);城市数,m城市间道路数,v是阿杜所住城市。第2至m+1行是每条路的信息,每行三个整数,为道路的起点、终点和两城市间距离。(城市从0开始编号)
【输出格式】
n组(按城市编号由小至大),每组三行
第一行:城市编号及一个冒号
第二行:path及一个冒号,后面是最短路径节点编号序列(编号间用一个空格隔开)
第三行:cost及一个冒号,后面是一个整数,表示路径距离
如果没有通路则输出 no
【输入样例】
6 8 0
0 2 10
0 4 30
0 5 100
1 2 5
2 3 50
3 5 10
4 3 20
4 5 60
【输出样例】
0:
no
1:
no
2:
path:0 2
cost:10
3:
path:0 4 3
cost:50
4:
path:0 4
cost:30
5:
path:0 4 3 5
cost:60
思路
就是一个简单的单源求最短路,由于是稀疏图,所以可以利用spfa方法求解.
#include<fstream>
#include<stack>
#include<queue>
#define INF 0x7fffffff
using namespace std;
ifstream cin("djs.in");
ofstream cout("djs.out");
int n,m,v;
int map[100][100];
void spfa(int t) {
cout<<t<<":"<<endl;
if(t==v) {
cout<<"no"<<endl;
return;
}
queue<int>tmp;
stack<int>mmp;
int dist[100];
int vis[100]= {0};
int path[100];
for(int i=0; i<n; i++) {
dist[i]=INF;
path[i]=-1;
}
vis[v]=1;
tmp.push(v);
dist[v]=0;
while(!tmp.empty()) {
int cur=tmp.front();
tmp.pop();
for(int i=0; i<n; i++) {
if(map[cur][i]!=0) {
if(dist[i]==INF) {
dist[i]=dist[cur]+map[cur][i];
path[i]=cur;
} else {
if(dist[i]>dist[cur]+map[cur][i]) {
dist[i]=dist[cur]+map[cur][i];
path[i]=cur;
}
}
if(!vis[i]) {
vis[i]=1;
tmp.push(i);
}
}
}
}
if(dist[t]==INF)
cout<<"no"<<endl;
else {
cout<<"path:";
for(int i=t;path[i]!=-1;i=path[i])
mmp.push(i);
mmp.push(v);
while(!mmp.empty())
{
cout<<mmp.top()<<" ";
mmp.pop();
}
cout<<endl;
cout<<"cost:"<<dist[t]<<endl;
}
}
int main() {
cin>>n>>m>>v;
for(int i=0; i<m; i++) {
int s,t,w;
cin>>s>>t>>w;
map[s][t]=w;
}
for(int i=0; i<n; i++) {
spfa(i);
}
return 0;
}