QOJ.ac
QOJ
ID | Problem | Submitter | Result | Time | Memory | Language | File size | Submit time | Judge time |
---|---|---|---|---|---|---|---|---|---|
#692375 | #5439. Meet in the Middle | NATO | RE | 0ms | 0kb | C++23 | 3.0kb | 2024-10-31 14:24:37 | 2024-10-31 14:24:38 |
answer
#include <bits/stdc++.h>
#define ll long long
#define INF 214748364719260817ll
#define MAXN 2147483647ll
using namespace std;
ll n, m;
struct graph {
ll head[100005], cnt;
struct ed {
ll v, next, w;
} edge[200005];
void add(ll u, ll v, ll w) {
edge[++cnt].v = v;
edge[cnt].next = head[u];
head[u] = cnt;
edge[cnt].w = w;
edge[++cnt].v = u;
edge[cnt].next = head[v];
head[v] = cnt;
edge[cnt].w = w;
}
int f[200005][20];
ll tot, lg[200005], dfn[200005], dep[200005], dis[200005];
int from[200005][20];
void clear() {
for (ll i = 1; i <= n; ++i) head[i] = 0;
cnt = tot = 0;
}
void dfs(ll id, ll fa) {
dep[id] = dep[fa] + 1;
f[dfn[id] = ++tot][0] = f[dfn[fa]][0] + 1;
from[dfn[id]][0] = id;
for (ll i = head[id]; i; i = edge[i].next) {
ll v = edge[i].v, w = edge[i].w;
if (v == fa)
continue;
dis[v] = dis[id] + w;
dfs(v, id);
f[++tot][0] = dep[id];
from[tot][0] = id;
}
}
ll get_lca(ll u, ll v) {
if (dfn[u] > dfn[v])
swap(u, v);
ll use = lg[dfn[v] - dfn[u] + 1];
ll r1 = from[dfn[u]][use], r2 = from[dfn[v] - (1 << use) + 1][use];
return dep[r1] < dep[r2] ? r1 : r2;
}
void init() {
ll u, v, w;
for (ll i = 1; i < n; ++i) cin >> u >> v >> w, add(u, v, w);
for (ll i = 2; i <= 2 * n - 1; ++i) lg[i] = lg[i >> 1] + 1;
dfs(1, 0);
for (ll i = tot; i > 0; --i)
for (ll j = 1; (i + (1 << j) - 1) <= tot; ++j) {
f[i][j] = f[i][j - 1];
from[i][j] = from[i][j - 1];
if (f[i][j] > f[i + (1 << (j - 1))][j - 1])
f[i][j] = f[i + (1 << (j - 1))][j - 1], from[i][j] = from[i + (1 << (j - 1))][j - 1];
}
}
ll get_dis(ll u, ll v) { return dis[u] + dis[v] - 2 * dis[get_lca(u, v)]; }
} g[2];
ll t;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin >> t;
random_device my;
mt19937 rd(my());
while (t--) {
g[0].clear();
g[1].clear();
cin >> n;
g[0].init();
g[1].init();
set<ll> p;
for (ll i = 1; i <= 200; ++i) {
ll u = rd() % n + 1, v = rd() % n + 1;
ll maxn = -1, uid = 0;
for (ll j = 1; j <= n; ++j) {
ll val = g[0].get_dis(u, j) + g[1].get_dis(v, j);
if (val > maxn)
maxn = val, uid = j;
}
p.insert(uid);
}
cin >> m;
while (m--) {
ll u, v;
cin >> u >> v;
ll maxn = -1;
for (auto it : p) {
ll val = g[0].get_dis(u, it) + g[1].get_dis(v, it);
maxn = max(maxn, val);
}
cout << maxn << '\n';
}
}
}
Details
Tip: Click on the bar to expand more detailed information
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