题目描述 传送门
正反向Dijkstra,枚举商业线。
坑点:最后输出路径,格式。
代码
#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<queue>
#include<stack>
using namespace std;
const int maxn=505,maxm=1005;
const int INF=1e9;
int n,s,e,m,x,y,z,k;
struct Edge{
int t,d,nxt;
Edge(int a=0,int b=0,int c=0):t(a),d(b),nxt(c){}
}edges[maxm*2];
struct heap{
int d,v;
heap(int a=0,int b=0):d(a),v(b){}
bool operator<(const heap&a)const{
return d>a.d;
}
};
int h[maxn],cnt,d1[maxn],d2[maxn],p1[maxn],p2[maxn];
bool vis[maxn];
void addedge(int from,int to,int dist){
edges[++cnt]=Edge(to,dist,h[from]);
h[from]=cnt;
edges[++cnt]=Edge(from,dist,h[to]);
h[to]=cnt;
}
int main(){
bool case1=1;
while(scanf("%d %d %d",&n,&s,&e)!=EOF){
cnt=0;
scanf("%d",&m);
if(!case1) puts("");
else case1=0;
memset(h,0,sizeof(h));
for(int i=0;i<m;i++){
scanf("%d%d%d",&x,&y,&z);
addedge(x,y,z);
}
for(int i=1;i<=n;i++) d1[i]=d2[i]=INF;
priority_queue<heap>q;
memset(vis,0,sizeof(vis));
q.push(heap(0,s));
d1[s]=0;
while(!q.empty()){
heap x=q.top();q.pop();
int u=x.v;
if(vis[u]) continue;
vis[u]=1;
for(int i=h[u];i;i=edges[i].nxt){
int v=edges[i].t;
if(d1[u]+edges[i].d<d1[v]){
d1[v]=d1[u]+edges[i].d;
p1[v]=u;
q.push(heap(d1[v],v));
}
}
}
memset(vis,0,sizeof(vis));
q.push(heap(0,e));
d2[e]=0;
while(!q.empty()){
heap x=q.top();q.pop();
int u=x.v;
if(vis[u]) continue;
vis[u]=1;
for(int i=h[u];i;i=edges[i].nxt){
int v=edges[i].t;
if(d2[u]+edges[i].d<d2[v]){
d2[v]=d2[u]+edges[i].d;
p2[v]=u;
q.push(heap(d2[v],v));
}
}
}
cin>>k;
int ans=d1[e],ansx=-1,ax,ay,o;
for(int i=0;i<k;i++){
scanf("%d%d%d",&x,&y,&z);
int a=d1[x]+d2[y]+z,b=d1[y]+d2[x]+z,k,nx=x,ny=y;
if(a<b) k=a;
else k=b,swap(nx,ny);
if(k<ans) ans=k,ansx=nx,ax=nx,ay=ny;
}
if(ansx==-1){
stack<int> stk;
int k=e;
for(;;){
stk.push(k);
if(k==s) break;
k=p1[k];
}
while(!stk.empty()) printf("%d%c",stk.top(),stk.top()==e?'\n':' '),stk.pop();
puts("Ticket Not Used");
}
else{
stack<int> stk;
int k=ax;
for(;;){
stk.push(k);
if(k==s) break;
k=p1[k];
}
while(!stk.empty()) printf("%d ",stk.top()),stk.pop();
k=ay;
for(;;){
printf("%d%c",k,k==e?'\n':' ');
if(k==e) break;
k=p2[k];
}
printf("%d\n",ansx);
}
printf("%d\n",ans);
}
}