输入样例:
4 5 0 3
0 1 1 20
1 3 2 30
0 3 4 10
0 2 2 20
2 3 1 20
输出样例:
0 2 3 3 40
#include<bits/stdc++.h>
using namespace std;
const int N=510;
int n,m,s,d;
int dist[N],sum[N],cost[N][N];
int g[N][N];
bool st[N];
int pre[N];//pre[x]=t代表x是从t走过来的,输出的时候反着推
void dijk()
{
memset(dist,0x3f,sizeof dist);
memset(sum,0x3f,sizeof sum);
sum[s]=0;
dist[s]=0;
for(int i=0;i<n;i++)
{
int t=-1;
for(int j=0;j<n;j++)
{
if(!st[j]&&(t==-1||dist[t]>dist[j])) t=j;
}
st[t]=1;
for(int j=0;j<n;j++)
{
if(dist[j]==dist[t]+g[t][j])
{
if(sum[j]>sum[t]+cost[t][j])
{
sum[j]=sum[t]+cost[t][j];
pre[j]=t; //路径记录
}
}
if(dist[j]>dist[t]+g[t][j])
{
dist[j]=dist[t]+g[t][j];
sum[j]=sum[t]+cost[t][j];
pre[j]=t; //路径记录
}
}
}
}
int main()
{
scanf("%d %d %d %d",&n,&m,&s,&d);
memset(g,0x3f,sizeof g);
memset(cost,0x3f,sizeof cost);
while(m--)
{
int a,b,c,co;
cin>>a>>b>>c>>co;
g[a][b]=g[b][a]=min(g[a][b],c);
cost[a][b]=cost[b][a]=min(cost[a][b],co);
}
dijk();
vector<int>path;
for(int i=d;i!=s;i=pre[i]){
path.push_back(i);
}//寻找路径
cout<<s<<" ";
for(int i=path.size()-1;i>=0;i--) cout<<path[i]<<" ";//输出路径
cout<<dist[d]<<" "<<sum[d]<<endl;
return 0;
}