题解:P14966 Staring at Stars

· · 题解

如果没发现选择 t=1 是不劣的应该怎么做?

我们先把流星按 x 坐标分组,注意到 \lfloor k/t\rfloor 只有 O(\sqrt k) 种不同的取值。对于每种取值 d,对应的 t 可取的范围是 [\lfloor k/(d+1)\rfloor+1,\lfloor k/d\rfloor]。由于 s 关于 t 非减,最大值一定在 t=\lfloor k/d\rfloor 处取得。因此我们只需要检查所有 t=\lfloor k/d\rfloor 的值即可。

对于每个 x 组,我们已按 y 排序,设该组有 m 个点,坐标为 y_1<y_2<\dots<y_m,亮度为 d_1,d_2,\dots,d_m。定义 g(t) 为选择区间 [b,b+t](b 为整数)能覆盖的点的最大亮度之和。由于亮度均为正,g(t) 等于满足 y_j-y_i\le t 的子串 [i,j] 的最大亮度之和,可以用双指针算法在 O(m) 时间内计算。

对于每个 t,若 t 大于等于该组 y 坐标的跨度(即 y_m-y_1),则 g(t) 等于所有点亮度之和,否则用双指针计算。

时间复杂度为 O(n\sqrt{k}),且常数较小,可以通过。

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;

int n,k;

int main(){
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);
    int T;
    cin>>T;
    while (T--){
        cin>>n>>k;
        unordered_map<int,unordered_map<int,int>> m;
        unordered_map<int,vector<pair<int,int>>> mp;
        for (int i=1;i<=n;i++){
            int x,y,d;
            cin>>x>>y>>d;
            m[x][y]=d; // 需要去重
        }
        for (auto &[x,tmp]:m){
            for (auto &[y,d]:tmp){
                mp[x].push_back({y,d});
            }
        }
        vector<int> v;
        for (int i=1,last;i<=k;i=last+1){
            int d=k/i,t=k/d;
            v.push_back(t);
            last=t;
        }
        sort(v.begin(),v.end());
        v.erase(unique(v.begin(),v.end()),v.end());
        ll ans=0;
        for (auto &[_,p]:mp){
            sort(p.begin(),p.end());
            ll tot=0;
            int miny=p[0].first,maxy=p[0].first;
            for (auto [u,v]:p){
                tot+=v;
                miny=min(miny,u);
                maxy=max(maxy,u);
            }
            int d=maxy-miny;
            for (int t:v){
                if (tot*(k/t)<=ans) continue; // 一定不优,剪枝
                ll s=0;
                if (t>=d) s=tot;
                else{
                    ll curr=0,maxn=0;
                    for (int l=0,r=0;r<int(p.size());r++){
                        curr+=p[r].second;
                        for (;l<int(p.size()) and p[r].first-p[l].first>t;l++) curr-=p[l].second;
                        maxn=max(maxn,curr);
                        if (maxn==tot) break;
                    }
                    s=maxn;
                }
                ans=max(ans,s*(k/t));
            }
        }
        cout<<ans<<"\n";
    }
    return 0;
}