题解:P9809 [SHOI2006] 作业 Homework

· · 题解

preface

蒟蒻初学根号分治,写篇题解纪念一下。

problem

题目传送门。

solution

对于这道题,我们可以想到一种暴力做法:

  1. 将 X 直接插入集合中。

  2. 枚举 k 使得 k\cdot Y\le3\times10^5 且 k\ge0,将最优策略更新为集合中第一个大于等于 k\cdot Y 的数,使用二分。

设值域大小为 V,插入元素 \mathcal{O}(\log n),查询元素 \mathcal{O}(V\log n),总时间复杂度为 \mathcal{O}(nV\log n),但别急,还有另一种暴力:

  1. 枚举 k 使得 1\le k\le3\times10^5,更新 Y=k 的答案。

  2. 直接输出答案值。

设值域大小为 V,更新答案 \mathcal{O}(V),查询元素 \mathcal{O}(1),总时间复杂度为 \mathcal{O}(nV)。

那到底怎么做呢?根号分治!(看前言就知道了)

根号分治,就好比把这两种暴力揉成一块(分块表兄),你管一半,我管另一半,那具体管那一半呢?我们设置一个阈值 B,第一种暴力管 Y\ge B,第二种暴力管 Y<B,问题就解决了。

更具体地说:

  1. 将 x 插入集合后,枚举 k 使得 k<B,更新 Y=k 的答案。

  2. 分为两种讨论:

设值域大小为 V,插入时间复杂度 \mathcal{O}(B),查询 Y<B 的时间复杂度为 \mathcal{O}(1),查询 Y\ge B 的时间复杂度为 \mathcal{O}(\frac VB\log n),总时间复杂度为 \mathcal{O}(B+\frac VB\log n)。

那么阈值 B 取何值呢?根据我们学前班就学过的均值不等式,当 B=\sqrt n 时,总时间复杂度为最小值。

大家可以发现,其实根号分治重点在分治上而不是根号上。

code

:::warning[愣着干嘛?还不快写!就想 ctj 是吧!]

#include<bits/stdc++.h>
using namespace std;
const int B = sqrt(300000);
int n,ans[B];
set<int> st;
int main(){
    memset(ans,0x3f,sizeof ans);
    for (cin >> n; n--; ){
        char c;
        int x;
        cin >> c >> x;
        if (c == 'A'){
            st.insert(x);
            for (int i = 1; i < B; i++) ans[i] = min(ans[i],x % i);
        }
        else{
            if (x < B) cout << ans[x] << '\n';
            else{
                int res = 1e9;
                for (int i = 0; x * i <= 3e5; i++){
                    if (st.lower_bound(x * i) == st.end()) break;
                    res = min(res,*st.lower_bound(x * i) - x * i);
                }
                cout << res << '\n';
            }
        }
    }
    return 0;
}

:::