This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
#define inf (2000000000)
#define N 100050
#define logn 20
#define f first
#define s second
using namespace std;
typedef pair<int, int> pii;
struct E
{
int a, b, c;
} A[N];
bool cmp(E A, E B) {
return A.c > B.c;
}
int n, m, q, id, pai[N], peso[N], nivel[N], anc[N][logn], best[N][logn];
vector<pii> grafo[N], all[N];
void dfs(int x, int p)
{
nivel[x] = nivel[p] + 1;
anc[x][0] = p;
for(auto v: grafo[x])
{
if(v.f == p) continue;
dfs(v.f, x);
best[v.f][0] = v.s;
}
}
int query(int u, int v)
{
if(nivel[u] < nivel[v]) swap(u, v);
int resp = m;
for(int i = logn - 1; i >= 0; i--)
if(nivel[u] - (1<<i) >= nivel[v])
resp = min(resp, best[u][i]), u = anc[u][i];
if(u == v) return resp;
for(int i = logn - 1; i >= 0; i--)
if(anc[u][i] != -1 && anc[u][i] != anc[v][i])
resp = min(min(resp, best[u][i]), best[v][i]), u = anc[u][i], v = anc[v][i];
return min(min(resp, best[u][0]), best[v][0]);
}
int Find(int x)
{
if(x == pai[x]) return x;
return pai[x] = Find(pai[x]);
}
void join(int a, int b)
{
a = Find(a), b = Find(b);
if(a == b) return;
if(peso[a] > peso[b]) pai[b] = a;
else if(peso[a] < peso[b]) pai[a] = b;
else pai[a] = b, peso[b] ++;
}
int main()
{
ios::sync_with_stdio(false); cin.tie(0);
cin>>n>>m>>q;
for(int i = m; i >= 1; i--)
{
for(int j = 1; i * j <= n; j++)
{
++id;
A[id] = {i, i*j, i};
}
}
sort(A + 1, A + id + 1, cmp);
for(int i = 1; i <= n; i++) pai[i] = i;
for(int i = 1; i <= id; i++)
{
int u = A[i].a, v = A[i].b, c = A[i].c;
if(Find(u) == Find(v)) continue;
join(u, v);
grafo[u].push_back({v, c});
grafo[v].push_back({u, c});
}
memset(anc, -1, sizeof anc);
dfs(1, 1);
for(int j = 1; j < logn; j++)
{
for(int i = 1; i <= n; i++)
{
if(anc[i][j-1] != -1) anc[i][j] = anc[anc[i][j - 1]][j-1];//anc[anc[i][j - 1]][j - 1];
if(anc[i][j - 1] != -1) best[i][j] = min(best[anc[i][j - 1]][j - 1], best[i][j - 1]);
}
}
for(int i = 1, u, v; i <= q; i++)
{
cin>>u>>v;
int ans = query(u, v);
cout<<m - ans + 1<<'\n';
}
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |