QOJ.ac

QOJ

ID题目提交者结果用时内存语言文件大小提交时间测评时间
#692377#5439. Meet in the MiddleraywuRE 0ms0kbC++142.1kb2024-10-31 14:24:392024-10-31 14:24:44

Judging History

你现在查看的是最新测评结果

  • [2024-10-31 14:24:44]
  • 评测
  • 测评结果:RE
  • 用时:0ms
  • 内存:0kb
  • [2024-10-31 14:24:39]
  • 提交

answer

#include <bits/stdc++.h>
#define _for(i, a, b)  for (int i = (a); i <= (b); i ++ )
#define _all(i, a, b)  for (int i = (a); i >= (b); i -- )
#define ll long long
#define P pair<int, int>
#define F first
#define S second
#define mp make_pair
#define pb push_back
using namespace std;
const int N = 1e5 + 5;
int n, q, pos, vis[N]; ll ans, x; mt19937 rnd(time(0)); vector<int> Ans;
struct Tree {
	int dfn_cnt, a[N], rk[N], dep[N], fa[N], dfn[N], top[N], sz[N], son[N]; vector<P > G[N]; ll f[N];
	void dfs1(int u) {
		sz[u] = 1, son[u] = - 1;
		for (P v : G[u])  if (v.F ^ fa[u]) {
			dep[v.F] = dep[u] + 1, fa[v.F] = u, f[v.F] = f[u] + v.S, dfs1(v.F), sz[u] += sz[v.F];
			if (son[u] == - 1 || sz[v.F] > sz[son[u]])  son[u] = v.F;
		}
	}
	void dfs2(int u, int Top) {
		dfn[u] = ++ dfn_cnt, rk[dfn_cnt] = u, top[u] = Top;
		if (son[u] == -1)  return ;
		dfs2(son[u], Top);
		for (P v : G[u])  if (v.F ^ fa[u] && v.F ^ son[u])  dfs2(v.F, v.F);
	}
	inline int lca(int u, int v) {
		int U = top[u], V = top[v];
		while (U ^ V) {
			if (dep[U] >= dep[V])  u = fa[U];
			else  v = fa[V];
			U = top[u], V = top[v];
		}
		return (dep[u] < dep[v] ? u : v);
	}
	inline ll dist(int u, int v) { return f[u] + f[v] - 2ll * f[lca(u, v)]; }
} T[2];
inline void solve() {
	cin >> n, Ans.clear(), T[0].dfn_cnt = T[1].dfn_cnt = 0; int u, v, w;
	_for (o, 0, 1)  _for (i, 1, n)  T[o].G[i].clear(), vis[i] = 0;
	_for (o, 0, 1)  _for (i, 2, n)  cin >> u >> v >> w, T[o].G[u].pb(mp(v, w)), T[o].G[v].pb(mp(u, w));
	_for (o, 0, 1)  T[o].dfs1(1), T[o].dfs2(1, 1);
	cin >> q;
	_for (_, 1, 100) {
		u = rnd() % n + 1, v = rnd() % n + 1, ans = pos = 0;
		_for (i, 1, n)  if ((x = T[0].dist(u, i) + T[1].dist(v, i)) > ans)  ans = x, pos = i;
		if (! vis[pos])  Ans.push_back(pos), vis[pos] = 1;
		if (Ans.size() == 4)  break;
	}
	while (q -- ) {
		cin >> u >> v, ans = 0;
		for (int i : Ans)  ans = max(ans, T[0].dist(u, i) + T[1].dist(v, i));
		cout << ans << "\n";
	}
}
int main() {
	ios :: sync_with_stdio(false), cin.tie(0), cout.tie(0);
	int T; cin >> T;
	while (T -- )  solve();
	return 0;
}

详细

Test #1:

score: 0
Runtime Error

input:

3 4
1 2 1
2 3 2
1 2 2
2 3 1
1 1
1 2
2 1
2 2

output:


result: