[PAT] Class 1030 Travel Plan (30 points) (SPFA, DFS)

Meaning of the questions:

Input N, M, S, D (N, M <= 500,0 <S, D <N), the starting point of the next M input line one side, end, and by the time by spending. Seeking the minimum cost shortest path, this path comprising the input start and end points, and by the time by spending.

trick:

Half an hour to find bug is finally found to dis array initial value in the range of 1 ~ N, this question is from point 0 ~ N-1, so only the first set of data by the 0th, bit boundary to initialize change AC.

Code:

#define HAVE_STRUCT_TIMESPEC
#include<bits/stdc++.h>
using namespace std;
int n,m,s,d;
int a[507];
typedef struct road{
int x,y,z;
};
vector<road>edg[507];
vector<pair<int,int> >pre[507];
vector<pair<int,int> >tmp_path,path;
int dis[507];
bool vis[507];
int ans=1e9;
void spfa(){
for(int i=0;i<n;++i)
dis[i]=1e9;
dis[s]=0;
vis[s]=1;
queue<int>q;
q.push(s);
while(!q.empty()){
int x=q.front();
vis[x]=0;
q.pop();
for(int i=0;i<edg[x].size();++i){
int v=edg[x][i].x;
int w=edg[x][i].y;
int val=edg[x][i].z;
if(dis[v]>dis[x]+w){
dis[v]=dis[x]+w;
pre[v].clear();
pre[v].push_back({x,a[val]});
if(!vis[v]){
vis[v]=1;
q.push(v);
}
}
else if(dis[v]==dis[x]+w)
pre[v].push_back({x,a[val]});
}
}
}
void dfs(int x,int y){
if(x==s){
if(y<ans){
ans=y;
path=tmp_path;
}
}
tmp_path.push_back({x,y});
for(int i=0;i<pre[x].size();++i)
dfs(pre[x][i].first,y+pre[x][i].second);
tmp_path.pop_back();
}
int main(){
cin>>n>>m>>s>>d;
int u,v,w;
for(int i=1;i<=m;++i){
cin>>u>>v>>w>>a[i];
edg[u].push_back({v,w,i});
edg[v].push_back({u,w,i});
}
spfa();
dfs(d,0);
cout<<s<<" ";
for(int i=path.size()-1;i>=0;--i)
cout<<path[i].first<<" ";
cout<<dis[d]<<" "<<ans;
return 0;
}

Guess you like

Origin www.cnblogs.com/ldudxy/p/11505317.html