floyd求路径
#include<cstdio> #include<algorithm> #include<stack> using namespace std; const int maxn=1000; const int nil=20000000; int a[maxn][maxn],path[maxn][maxn]; stack<int>s; int main(){ int n; int m,x,y,w; scanf("%d%d",&n,&m); for (int i=1;i<=n;i++) for (int j=1;j<=n;j++) a[i][j]=nil,path[i][j]=-1; for (int i=1;i<=m;i++){ scanf("%d%d%d",&x,&y,&w); a[x][y]=w; a[y][x]=w; } for (int k=1;k<=n;k++){ for(int i=1;i<=n;i++){ for (int j=1;j<=n;j++){ if(a[i][j]>(a[i][k]+a[k][j])&&i!=j&&i!=k&&k!=j) { a[i][j]=a[i][k]+a[k][j]; path[i][j]=k; } } } } printf("%d\n",a[1][4]); printf("%d ",1); int k=4; while(path[1][k]!=-1){ k=path[1][k]; s.push(k); } while(!s.empty()){ printf("%d ",s.top()); s.pop(); } printf("%d ",4); return 0; }