一个人的旅行 HDU - 2066 dijkstra

题解

使用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;
}

猜你喜欢

转载自blog.csdn.net/CaprYang/article/details/85226097