#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <vector>
using namespace std;
const int inf=1111111111;
int G[510][510];
int d[510],cost[510][510];
bool vis[510];
vector<int> pre[510];
int N,M,st,ed;
void Dij(int st)
{
fill(vis,vis+510,false);
fill(d,d+510,inf);
d[st]=0;
for(int i=0;i<N;i++)
{
int u=-1,MIN=inf;
for(int j=0;j<N;j++)
{
if(vis[j]==false&&d[j]<MIN)
{
MIN=d[j];
u=j;
}
}
if(u==-1)return;
vis[u]=true;
for(int v=0;v<N;v++)
{
if(vis[v]==false&&G[u][v]<inf)
{
if(d[u]+G[u][v]<d[v])
{
pre[v].clear();
pre[v].push_back(u);
d[v]=d[u]+G[u][v];
}
else if(d[u]+G[u][v]==d[v])
{
pre[v].push_back(u);
}
}
}
}
}
int mincost=inf;
vector<int> path,temppath;
void DFS(int now)
{
if(now==st)
{
temppath.push_back(now);
int c=0;
for(int i=1;i<temppath.size();i++)
{
int c1=temppath[i];
int c2=temppath[i-1];
c+=cost[c1][c2];
}
if(c<mincost)
{
mincost=c;
path=temppath;
}
temppath.pop_back();
return;
}
temppath.push_back(now);
for(int i=0;i<pre[now].size();i++)
{
DFS(pre[now][i]);
}
temppath.pop_back();
}
int main()
{
scanf("%d%d%d%d",&N,&M,&st,&ed);
fill(G[0],G[0]+510*510,inf);
for(int i=0;i<M;i++)
{
int c1,c2,l,c;
scanf("%d%d%d%d",&c1,&c2,&l,&c);
G[c1][c2]=l;
G[c2][c1]=l;
cost[c1][c2]=c;
cost[c2][c1]=c;
}
Dij(st);
DFS(ed);
for(int i=path.size()-1;i>=0;i--)
{
printf("%d ",path[i]);
}
printf("%d %d",d[ed],mincost);
return 0;
}
PAT甲1030 Travel Plan (30)(30 分)
最新推荐文章于 2023-02-16 15:00:28 发布