#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e5+10;
int pai[maxn], sz[maxn], edge[maxn], nivel[maxn];
int Find(int x)
{
if (pai[x] == x) return x;
return Find(pai[x]);
}
void Join(int x, int y, int tt)
{
x = Find(x), y = Find(y);
if (x == y) return;
if (sz[x] < sz[y]) swap(x, y);
sz[x] += sz[y], pai[y] = x, edge[y] = tt;
}
void init(int n)
{
for (int i = 1; i <= n; i++)
pai[i] = i, sz[i] = 1;
}
int dfs(int u)
{
if (u == Find(1)) return 0;
return nivel[u] = dfs(pai[u])+1;
}
int lca(int u, int v)
{
int ans = -1;
while (u != v)
{
if (nivel[u] > nivel[v]) ans = max(ans, edge[u]), u = pai[u];
else ans = max(ans, edge[v]), v = pai[v];
}
return ans;
}
int main(void)
{
ios::sync_with_stdio(false); cin.tie(0);
int n, m, q;
cin >> n >> m >> q;
init(n);
for (int i = m; i >= 1; i--)
for (int j = i; j <= n; j += i)
Join(j, i, m-i+1);
for (int i = 1; i <= n; i++)
dfs(i);
for (int i = 1; i <= q; i++)
{
int u, v;
cin >> u >> v;
cout << lca(u, v) << "\n";
}
}
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
4 ms |
376 KB |
Output is correct |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
7 ms |
548 KB |
Output is correct |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
21 ms |
688 KB |
Output is correct |
2 |
Correct |
21 ms |
732 KB |
Output is correct |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
31 ms |
892 KB |
Output is correct |
2 |
Correct |
27 ms |
892 KB |
Output is correct |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
21 ms |
1020 KB |
Output is correct |
2 |
Correct |
24 ms |
1276 KB |
Output is correct |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
23 ms |
1364 KB |
Output is correct |
2 |
Correct |
24 ms |
1492 KB |
Output is correct |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
35 ms |
1664 KB |
Output is correct |
2 |
Correct |
27 ms |
1664 KB |
Output is correct |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
31 ms |
1868 KB |
Output is correct |
2 |
Correct |
43 ms |
2092 KB |
Output is correct |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
49 ms |
2444 KB |
Output is correct |
2 |
Correct |
51 ms |
2444 KB |
Output is correct |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
64 ms |
2684 KB |
Output is correct |
2 |
Correct |
62 ms |
2684 KB |
Output is correct |