一個人的旅行 HDU - 2066 dijkstra
阿新 • • 發佈:2019-01-13
題解
使用dijkstra演算法+堆優化 處理時將所有起點加入佇列並設定起點代價為0 跑完最短路在所有終點中選代價最小的一個
注意為無向圖
AC程式碼
#include <stdio.h>
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int INF = 0x3f3f3f3f;
const int MAXN = 5e5 + 10;
int N, S, D; //路徑 起點 終點
int a[MAXN];
ll cot[MAXN];
int vis[MAXN] ;
struct node
{
int v, w;
bool operator < (const node &oth) const
{
return w > oth.w;
}
};
vector<node> edge[MAXN];
void dij()
{
memset(cot, 0x3f, sizeof(cot));
memset(vis, 0, sizeof(vis));
priority_queue<node> pq;
for (int i = 0; i < S; i++)
pq.push(node{ a[i], 0 } ), cot[a[i]] = 0; //將所有起點加入佇列並將代價設定為0
while (!pq.empty())
{
int u = pq.top().v;
ll w = pq.top().w;
vis[u] = 1;
pq.pop();
for (int i = 0; i < edge[u].size(); i++)
{
int v = edge[u][i].v, c = edge[u][i].w;
if (!vis[v] && cot[v] > cot[u] + c)
{
cot[v] = cot[u] + c;
pq. push(node{ v, cot[u] + c });
}
}
}
}
int main()
{
#ifdef LOCAL
freopen("C:/input.txt", "r", stdin);
#endif
while (cin >> N >> S >> D)
{
for (int i = 0; i < 10000; i++)
edge[i].clear();
for (int i = 0; i < N; i++)
{
int u, v, w;
scanf("%d%d%d", &u, &v, &w);
edge[u].push_back(node{ v, w });
edge[v].push_back(node{ u, w });
}
for (int i = 0; i < S; i++)
scanf("%d", &a[i]);
dij();
ll ans = 1e18;
for (int i = 0; i < D; i++)
{
int b;
scanf("%d", &b);
ans = min(ans, cot[b]);
}
cout << ans << endl;
}
return 0;
}