「CF1051F」The Shortest Statement

传送门
Luogu

解题思路

注意到 \(m - n \le 20\) ,所以这其实是一个树上问题,非树边至多只有21条,那么我们就可以暴力地对每一个非树边所连接的点求一次单源最短路,然后每次询问时,先访问两点的树上距离,再尝试用非树边更新答案,取最小值输出即可。

细节注意事项

  • 最短路不要写挂就好

参考代码

#include <algorithm>
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <cctype>
#include <cmath>
#include <ctime>
#include <vector>
#include <queue>
#define rg register
using namespace std;
template < typename T > inline void read(T& s) {
 	s = 0; int f = 0; char c = getchar();
 	while (!isdigit(c)) f |= (c == '-'), c = getchar();
 	while (isdigit(c)) s = s * 10 + (c ^ 48), c = getchar();
 	s = f ? -s : s;
}

typedef long long LL;
const int _ = 100010;
const int __ = 200010;

int tot = 1, head[_], nxt[__], ver[__], w[__];
inline void Add_edge(int u, int v, int d)
{ nxt[++tot] = head[u], head[u] = tot, ver[tot] = v, w[tot] = d; }

int n, m, q, f[22][_], dep[_];
int vis[_], mark[__], sign[_];
LL tdis[_], dis[50][_];
vector < int > vec;

inline void dfs(int u) {
	vis[u] = 1;
	for (rg int i = head[u]; i; i = nxt[i]) {
		int v = ver[i]; if (vis[v]) continue;
		f[0][v] = u, dep[v] = dep[u] + 1;
		tdis[v] = tdis[u] + (LL) w[i];
		mark[i] = mark[i ^ 1] = 1, dfs(v);
	}
}

inline void calc() {
	for (rg int i = 1; i <= 20; ++i)
		for (rg int j = 1; j <= n; ++j)
			f[i][j] = f[i - 1][f[i - 1][j]];
}

inline int LCA(int x, int y) {
	if (dep[x] < dep[y]) swap(x, y);
	for (rg int i = 20; ~i; --i)
		if (dep[f[i][x]] >= dep[y]) x = f[i][x];
	if (x == y) return x;
	for (rg int i = 20; ~i; --i)
		if (f[i][x] != f[i][y]) x = f[i][x], y = f[i][y];
	return f[0][x];
}

inline void Dijkstra(int s, int p) {
	static priority_queue < pair < LL, int > > Q;
	memset(vis, 0, sizeof vis);
	memset(dis[p], 0x7f, sizeof dis[p]);
	dis[p][s] = 0, Q.push(make_pair(0, s));
	while (!Q.empty()) {
		int u = Q.top().second; Q.pop();
		if (vis[u]) continue; vis[u] = 1;
		for (rg int i = head[u]; i; i = nxt[i]) {
			int v = ver[i];
			if (dis[p][v] > dis[p][u] + w[i])
				dis[p][v] = dis[p][u] + w[i], Q.push(make_pair(-dis[p][v], v));
		}
	}
}

inline LL solve(int x, int y) {
	LL res = tdis[x] + tdis[y] - 2 * tdis[LCA(x, y)];
	for (rg int i = 0; i < (int) vec.size(); ++i)
		res = min(res, dis[i][x] + dis[i][y]);
	return res;
}

int main() {
#ifndef ONLINE_JUDGE
	freopen("in.in", "r", stdin);
#endif
	read(n), read(m);
	for (rg int u, v, d, i = 1; i <= m; ++i)
		read(u), read(v), read(d), Add_edge(u, v, d), Add_edge(v, u, d);
	dfs(1), calc();
	for (rg int i = 2; i <= tot; ++i)
		if (!mark[i] && !sign[ver[i]])
			vec.push_back(ver[i]), sign[ver[i]] = 1;
	for (rg int i = 0; i < (int) vec.size(); ++i) Dijkstra(vec[i], i);
	read(q); for (rg int x, y; q--; ) read(x), read(y), printf("%lld\n", solve(x, y));
	return 0;
}

完结撒花 \(qwq\)

posted @ 2019-10-26 22:24  Sangber  阅读(164)  评论(0编辑  收藏  举报