货车运输(详细揭秘)

一个 \(\log\) 的树剖解法!!!

好吧不滥用标题行了 .

注意到没有修改,轻重链剖分,链用 st 表维护,时间复杂度 \(O(q\log n)\) .

#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <ctime>
#include <vector>
#include <queue>
#include <cmath>
#include <map>
#include <set>
using namespace std;
inline int chkmin(int& a, const int& b){if (a > b) a = b; return a;}
const int N = 12345, M = 51411, LgN = 11+4.514, INF = 0x3f3f3f3f;
typedef pair<int, int> pii;
int n, m, w[N];
int fa[N], dep[N], siz[N], son[N], top[N], dfn[N], rnk[N], cc;
vector<pii> g[N];
inline void addedge(int u, int v, int w){g[u].emplace_back(make_pair(v, w));}
inline void ade(int u, int v, int w){addedge(u, v, w); addedge(v, u, w);}
struct Edge{int u, v, w; bool operator < (const Edge& _)const{return w > _.w;}}ed[M];
struct dsu
{
	int fa[N];
	int fnd(int x){return x == fa[x] ? x : fa[x] = fnd(fa[x]);}
	inline void merge(int u, int v){fa[fnd(u)] = fnd(v);}
	inline bool same(int u, int v){return fnd(u) == fnd(v);}
	void init(int n){for (int i=1; i<=n; i++) fa[i] = i;}
}D;
struct st
{
	int f[N][LgN];
	inline void init()
	{
		for (int i=1; i<=n; i++) f[i][0] = w[rnk[i]];
		for (int j=1; (1<<j)<=n; j++)
			for (int i=1; i+(1<<j)-1<=n; i++) f[i][j] = min(f[i][j-1], f[i+(1<<(j-1))][j-1]);
	}
	inline int query(int l, int r){int _ = log2(r-l+1); return min(f[l][_], f[r-(1<<_)+1][_]);}
}T;
void dfs1(int u)
{
	siz[u] = 1;
	for (auto e : g[u])
	{
		int v = e.first, _ = e.second;
		if (v == fa[u]) continue;
		fa[v] = u; dep[v] = dep[u] + 1;
		dfs1(v);
		siz[v] += siz[u]; w[v] = _;
		if (!son[u] || (siz[son[u]] < siz[v])) son[u] = v;
	}
}
void dfs2(int u, int t)
{
	top[u] = t;
	rnk[++cc] = u; dfn[u] = cc;
	if (!son[u]) return ;
	dfs2(son[u], t);
	for (auto e : g[u])
		if ((e.first != fa[u]) && (e.first != son[u])) dfs2(e.first, e.first);
}
int query(int u, int v)
{
	int ans=INF, fu=top[u], fv=top[v];
	while (fu != fv)
	{
		if (dep[fu] > dep[fv]){chkmin(ans, T.query(dfn[fu], dfn[u])); u = fa[fu];}
		else{chkmin(ans, T.query(dfn[fv], dfn[v])); v = fa[fv];}
		fu = top[u]; fv = top[v];
	}
	if (dep[u] > dep[v]) swap(u, v);
	if (u != v) chkmin(ans, T.query(dfn[u]+1, dfn[v]));
	return ans;
}
void Kruskal()
{
	sort(ed+1, ed+1+m); D.init(n);
	for (int i=1; i<=m; i++)
	{
		int u = ed[i].u, v = ed[i].v, w = ed[i].w;
		if (D.same(u, v)) continue;
		D.merge(u, v); ade(u, v, w);
	}
}
int main()
{
#ifndef ONLINE_JUDGE
	freopen("i.in", "r", stdin);
#endif
	scanf("%d%d", &n, &m);
	for (int i=1; i<=m; i++) scanf("%d%d%d", &ed[i].u, &ed[i].v, &ed[i].w);
	Kruskal(); dfs1(1); dfs2(1, 1); T.init();
	int q, u, v; scanf("%d", &q);
	while (q--)
	{
		scanf("%d%d", &u, &v);
		if (!D.same(u, v)) puts("-1");
		else printf("%d\n", query(u, v));
	}
	return 0;
}
posted @ 2022-02-07 19:43  Jijidawang  阅读(104)  评论(1编辑  收藏  举报
😅​