如果没发现选择 是不劣的应该怎么做?
我们先把流星按 坐标分组,注意到 只有 种不同的取值。对于每种取值 ,对应的 可取的范围是 。由于 关于 非减,最大值一定在 处取得。因此我们只需要检查所有 的值即可。
对于每个 组,我们已按 排序,设该组有 个点,坐标为 ,亮度为 。定义 为选择区间 ( 为整数)能覆盖的点的最大亮度之和。由于亮度均为正, 等于满足 的子串 的最大亮度之和,可以用双指针算法在 时间内计算。
对于每个 ,若 大于等于该组 坐标的跨度(即 ),则 等于所有点亮度之和,否则用双指针计算。
时间复杂度为 ,且常数较小,可以通过。
#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;
}