<span style="font-size:18px;">#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
using namespace std;
const int maxn=505,INF=10000000;
int S,E;
struct Edge
{
int from,to,dist;
};
struct HeapNode
{
int d,u;
bool operator < (const HeapNode& rhs) const
{
return d>rhs.d;
}
};
struct Dijkstra
{
int n,m;//?????
vector<Edge> edges;
vector<int> G[maxn];//??????????
bool done[maxn];//????????
int d[maxn];
int p[maxn];
void init(int n)
{
this->n=n;
for(int i=1;i<=n;i++) G[i].clear();//?????
edges.clear();
}
void AddEdge(int from,int to,int dist)
{
edges.push_back((Edge){from,to,dist});
m=edges.size();
G[from].push_back(m-1);
}
void dijkstra(int s)
{
priority_queue<HeapNode> Q;
for(int i=1;i<=n;i++) d[i]=INF;
d[s]=0;
memset(done,0,sizeof(done));
Q.push((HeapNode){0,s});//
while(!Q.empty())
{
HeapNode x=Q.top();
Q.pop();
int u=x.u;
if(done[u])continue;
done[u]=true;
for(int i=0;i<G[u].size();i++)
{
Edge& e=edges[G[u][i]];
if(d[e.to]>d[u]+e.dist)
{
d[e.to]=d[u]+e.dist;
p[e.to]=G[u][i];
Q.push((HeapNode){d[e.to],e.to});
}
}
}
}
void put1(int h)
{
if(h==S)
{
printf("%d",S);
return;
}
put1(edges[p[h]].from);
printf(" %d",h);
}
void put2(int h)
{
if(h==E)
{
printf(" %d\n",E);
return;
}
printf(" %d",h);
put2(edges[p[h]].from);
}
};
int main()
{
int N,X,Y,Z,ansl,ansr,kase;
Dijkstra a,b;
while(scanf("%d%d%d",&N,&S,&E)!=EOF)
{
if(kase++)printf("\n");
int M,K;
a.init(N);
b.init(N);
scanf("%d",&M);
while(M--)
{
scanf("%d%d%d",&X,&Y,&Z);
a.AddEdge(X,Y,Z);
a.AddEdge(Y,X,Z);
b.AddEdge(X,Y,Z);
b.AddEdge(Y,X,Z);
}
a.dijkstra(S);
b.dijkstra(E);
scanf("%d",&K);
int ans=a.d[E];
ansl=ansr=-1;
int tmp;
while(K--)
{
scanf("%d%d%d",&X,&Y,&Z);
tmp=a.d[X]+Z+b.d[Y];
if(ans>tmp)
{
ans=tmp;
ansl=X;
ansr=Y;
}
tmp=a.d[Y]+Z+b.d[X];
if(ans>tmp)
{
ans=tmp;
ansl=Y;
ansr=X;
}
}
//cout<<ansl<<" "<<ansr<<endl;
if(ansl!=-1)
{
a.put1(ansl);
b.put2(ansr);
printf("%d\n",ansl);
printf("%d\n",ans);
}
else
{
a.put1(E);
printf("\n");
printf("Ticket Not Used\n");
printf("%d\n",ans);
}
}
return 0;
}</span>
uva 11374(Dijkstra + 枚举)
最新推荐文章于 2020-10-06 17:47:39 发布