题解:P4631 [APIO2018] 选圆圈

· · 题解

感觉这个题很妙啊。

这篇题解主要讲解 O(n\log R) 的做法。

Solution

直接按照题意模拟是 O(n^2) 的,考虑优化,假设当前最大的圆半径为 R,那么我们把整个平面以 2R 为边长划分多个格子,那么如果两个圆相交,他们的圆心距离一定不超过 2R,所以我们只需要处理圆心在周围 9 个格子中的圆。每次如果当前处理的圆半径小于 \dfrac R2,就把 R 设为当前圆的半径进行重构,这样只会重构 O(\log R) 次。

然后分析一下时间复杂度:在划分的边长为 2R 时,我们会处理所有半径大于等于 \dfrac R2 的圆,而对于一个格子,只有 O(1) 个圆会被自己删掉,所以一个圆在一次划分中只会被检查 O(1) 次,因此总时间复杂度可以做到 O(n\log R)(需要精细实现)。

Code

//when you use vector or deque,pay attention to the size of it.
//by OldDriverTree
#include<bits/stdc++.h>
//#include<atcoder/all>
#define P pair<int,int>
#define int long long
#define mid (l+r>>1)
using namespace std;
//using namespace atcoder;
//using mint=modint998244353;
const int N=3e5+1;
map<P,vector<int> > a;
int n,x[N],y[N],r[N],p[N];
int now,ans[N];

struct custom_hash
{
    static uint64_t splitmix64(uint64_t x) {
        x+=0x9e3779b97f4a7c15;
        x=(x^(x>>30) )*0xbf58476d1ce4e5b9;
        x=(x^(x>>27) )*0x94d049bb133111eb;
        return x^(x>>31);
    }
    size_t operator() (uint64_t x) const {
        static const uint64_t FIXED_RANDOM=chrono::steady_clock::now().time_since_epoch().count();
        return splitmix64(x+FIXED_RANDOM);
    }
};
int read() {
    int x=0; bool _=true; char c=0;
    while (!isdigit(c) ) _&=(c!='-'),c=getchar();
    while (isdigit(c) ) x=x*10+(c&15),c=getchar();
    return _?x:-x;
}
bool check(int p,int q) {
    return (x[p]-x[q])*(x[p]-x[q])+(y[p]-y[q])*(y[p]-y[q])<=(r[p]+r[q])*(r[p]+r[q]);
}
main()
{
    n=read(); for (int i=1;i<=n;i++) x[i]=read(),y[i]=read(),r[i]=read(),p[i]=i;
    sort(p+1,p+n+1,[&](int x,int y){ return r[x]^r[y]?r[x]>r[y]:x<y; });
    for (int _=1;_<=n;_++)
    {
        int pos=p[_];
        if (ans[pos]) continue;
        if (!now||r[pos]*2<now/2) {
            now=r[pos]*2,a.clear();
            for (int i=1;i<=n;i++) if (!ans[i])
            a[{x[i]/now,y[i]/now}].push_back(i);
        }
        int px=x[pos]/now,py=y[pos]/now;
        for (int p=px-1;p<px+2;p++)
            for (int q=py-1;q<py+2;q++)
                if (a.find({p,q})!=a.end() ) {
                    vector<int> awa;
                    for (int x:a[{p,q}])
                    if (check(x,pos) ) ans[x]=pos;
                    else awa.push_back(x); a[{p,q}]=awa;
                }
    }
    for (int i=1;i<=n;i++)
    printf("%lld ",ans[i]);
    return 0;
}