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>
using namespace std;
using ii = pair<int, int>;
template <int maxn>
struct Dsu {
int pai[maxn], w[maxn];
int find(int x)
{
if (x == pai[x]) return x;
return pai[x] = find(pai[x]);
}
bool check(int a, int b)
{
a = find(a), b = find(b);
return a == b;
}
void join(int a, int b)
{
a = find(a), b = find(b);
if (a == b) return;
if (w[a] < w[b]) swap(a, b);
pai[b] = a;
w[a] += w[b];
}
void init(int n) {
fill(w+1, w+n+1, 1);
iota(pai+1, pai+n+1, 1);
}
};
struct Query
{
int ff, ss, id;
};
int const maxn = 101010;
int n, m, q, lk;
Dsu<maxn> dsu;
vector<Query> qr[maxn], nqr[maxn];
vector<ii> qe, nq;
int res[maxn];
void clear()
{
swap(qe, nq), swap(qr, nqr), lk = m+1, dsu.init(n);
}
void add(int k)
{
while (lk > k) {
--lk;
for (int j = 2*lk; j <= n; j += lk)
dsu.join(lk, j);
}
}
void split(int l, int k, int r)
{
bool isl = false, isr = false;
for (auto p : qr[l]) {
if (!dsu.check(p.ff, p.ss))
isl = true, nqr[l].push_back(p);
else
isr = true, nqr[k].push_back(p);
}
if (!isr) nq.push_back({k, r});
if (!isl) nq.push_back({l, k});
qr[l].clear();
}
void add_ans(int l)
{
for (auto p : qr[l]) {
res[p.id] = l;
}
}
int main()
{
ios::sync_with_stdio(false), cin.tie(0);
cin >> n >> m >> q;
dsu.init(n);
qe.push_back({1, m+1});
for (int i = 0; i < q; i++) {
int a, b;
cin >> a >> b;
qr[1].push_back({a, b, i});
}
lk = m+1;
for (auto pp : qe) {
int l, r;
tie(l, r) = pp;
add((l+r)/2);
if (l+1 < r) split(l, (l+r)/2, r);
else add_ans(l);
if (pp == qe.back()) clear();
}
for (int i = 0; i < q; i++) cout << m-res[i]+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... |