[题目链接]
https://www.lydsy.com/JudgeOnline/problem.php?id=2100
[算法]
Answer = min{ dist(PB,PA1) + dist(PA1,PA2) , dist(PB,PA2) + dist(PA1,PA2) } (其中,dist表示最短路)
对PB和PA1分别求两次最短路即可,注意要使用dijkstra算法(堆优化)
[代码]
#include<bits/stdc++.h> using namespace std; #define MAXP 100010 #define MAXC 200010 struct edge { int to,w,nxt; } e[MAXC << 1]; int i,C,P,PA1,PA2,PB,u,v,w,tot; int head[MAXP],dist1[MAXP],dist2[MAXP]; inline void addedge(int u,int v,int w) { tot++; e[tot] = (edge){v,w,head[u]}; head[u] = tot; } inline void dijkstra1() { int i,cur,v,w; static bool visited[MAXP]; priority_queue< pair<int,int> > q; memset(visited,false,sizeof(visited)); memset(dist1,0x3f,sizeof(dist1)); dist1[PB] = 0; q.push(make_pair(0,PB)); while (!q.empty()) { cur = q.top().second; q.pop(); if (visited[cur]) continue; visited[cur] = true; for (i = head[cur]; i; i = e[i].nxt) { v = e[i].to; w = e[i].w; if (dist1[cur] + w < dist1[v]) { dist1[v] = dist1[cur] + w; q.push(make_pair(-dist1[v],v)); } } } } inline void dijkstra2() { int i,cur,v,w; static bool visited[MAXP]; priority_queue< pair<int,int> > q; memset(visited,false,sizeof(visited)); memset(dist2,0x3f,sizeof(dist1)); dist2[PA1] = 0; q.push(make_pair(0,PA1)); while (!q.empty()) { cur = q.top().second; q.pop(); if (visited[cur]) continue; visited[cur] = true; for (i = head[cur]; i; i = e[i].nxt) { v = e[i].to; w = e[i].w; if (dist2[cur] + w < dist2[v]) { dist2[v] = dist2[cur] + w; q.push(make_pair(-dist2[v],v)); } } } } int main() { scanf("%d%d%d%d%d",&C,&P,&PB,&PA1,&PA2); for (i = 1; i <= C; i++) { scanf("%d%d%d",&u,&v,&w); addedge(u,v,w); addedge(v,u,w); } dijkstra1(); dijkstra2(); printf("%d ",min(dist1[PA1] + dist2[PA2],dist1[PA2] + dist2[PA2])); return 0; }