QOJ.ac
QOJ
ID | 题目 | 提交者 | 结果 | 用时 | 内存 | 语言 | 文件大小 | 提交时间 | 测评时间 |
---|---|---|---|---|---|---|---|---|---|
#692377 | #5439. Meet in the Middle | raywu | RE | 0ms | 0kb | C++14 | 2.1kb | 2024-10-31 14:24:39 | 2024-10-31 14:24:44 |
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