为什么不开O2就全错,开O2就全对呢?
查看原帖
为什么不开O2就全错,开O2就全对呢?
388257
我就是蓬蒿人楼主2021/12/21 20:28
#include <cstdio>
#include <climits>
#include <array>
#include <queue>
#include <bits/stl_pair.h>
#include <algorithm>

using namespace std;

using edge_t = pair<size_t, size_t>;
class list_node_t
{
public:
	size_t from, to, w;
	list_node_t *pNext;

	list_node_t() : from(0U), to(0U), w(0U), pNext(nullptr) {}
	list_node_t(size_t _from, size_t _to, size_t _w, list_node_t *_pNext)
		: from(_from), to(_to), w(_w), pNext(_pNext) {}
	list_node_t(const list_node_t &) = default;
	list_node_t(list_node_t &&) = default;

	list_node_t &operator=(const list_node_t &) = default;
};
using header_t = list_node_t *;

const size_t N = 5e4, S = 1U, INF = INT_MAX;
size_t a, b, c, d, e, m, n;
array<size_t, 6> sym = array<size_t, 6>({S});
array<array<size_t, N + 2>, 6> dist;
array<bool, N + 2> vis;
array<header_t, N + 2> nodes;

inline size_t min(size_t a, size_t b)
{
	return ((a < b) ? a : b);
}
inline void link(size_t from, size_t to, size_t w)
{
	nodes.at(from) = new list_node_t(from, to, w, nodes.at(from));
}
void dijkstra(size_t from);
inline void dijkstra()
{
	dijkstra(0U);
	sym.at(1) = a;
	dijkstra(1U);
	sym.at(2) = b;
	dijkstra(2U);
	sym.at(3) = c;
	dijkstra(3U);
	sym.at(4) = d;
	dijkstra(4U);
	sym.at(5) = e;
	dijkstra(5U);
}

int main()
{
	// freopen("P5764.in", "r", stdin);
	// freopen("P5764.out", "w", stdout);

	scanf("%u%u%u%u%u%u%u", &n, &m, &a, &b, &c, &d, &e);
	size_t u, v, w;
	while (m--)
	{
		scanf("%u%u%u", &u, &v, &w);
		link(u, v, w);
		link(v, u, w);
	}

	dijkstra();
	array<size_t, 5> perm = array<size_t, 5>({1, 2, 3, 4, 5});
	size_t minn = INF;
	do
	{
		minn = min(minn,
				   dist.at(0U).at(sym.at(perm.at(0U))) +
					   dist.at(perm.at(0U)).at(sym.at(perm.at(1U))) +
					   dist.at(perm.at(1U)).at(sym.at(perm.at(2U))) +
					   dist.at(perm.at(2U)).at(sym.at(perm.at(3U))) +
					   dist.at(perm.at(3U)).at(sym.at(perm.at(4U))));
	} while (next_permutation(perm.begin(), perm.end()));

	printf("%u\n", minn);

	return 0;
}

void dijkstra(size_t from)
{
	for (size_t i = 0; i <= n; ++i)
	{
		dist.at(from).at(i) = INF;
		vis.at(i) = false;
	}
	dist.at(from).at(sym.at(from)) = 0U;
	priority_queue<edge_t, vector<edge_t>, greater<edge_t>> pq;
	pq.push({0U, sym.at(from)});
	while (pq.size())
	{
		size_t to = pq.top().second;
		pq.pop();
		if (!vis.at(to))
		{
			vis.at(to) = true;
			for (list_node_t *p = nodes.at(to); p; p = p->pNext)
			{
				if (dist.at(from).at(p->to) > dist.at(from).at(to) + p->w)
				{
					pq.push({dist.at(from).at(p->to) =
								 dist.at(from).at(to) + p->w,
							 p->to});
				}
			}
		}
	}
}
2021/12/21 20:28
加载中...