跳到正文

题解

【1】做题心得 - 2026 NOICA #15 - T1【一次函数】【扫描线】【差分】

ExFish约 6 分钟
原文
文章信息与版本

文章信息

发布
2026年10月22日
收录
2026年10月23日
更新
2026年11月17日
篇幅
约 6 分钟

版本

  1. v1当前

我怎么啥都不会,赛时直接使用线段树大力书写炸了。

首先你发现答案的本质是在一个极大值域的数轴上加两侧夹角为 45°45\degree 的等腰梯形,然后最终的答案就是一个很混乱的分段函数,要你求出其极大值的位置。

我们来看这个等腰梯形的式子(如果左右侧不符合那么就调换顺序):

  • Li−riL_i-r_i,也就是直接移动到目标区间的最左侧,这是等腰梯形的左侧最小位置(l_bottom)。
  • Ri−liR_i-l_i,也就是直接移动到目标区间的最右侧,这是等腰梯形的右侧最小位置(r_bottom)。
  • Li−liL_i-l_i,让左端点重合,最大化覆盖,这是等腰梯形的左侧最大位置(l_top)。
  • Ri−riR_i-r_i,让右端点重合,最大化覆盖,这是等腰梯形的右侧最大位置(r_top)。

那么,我们注意到最大值只能在端点处取到,我们直接对这些一次函数扫描线,使用差分的思想,在端点处加贡献,然后取到全局最大值即可。

没想到的主要的原因就是没有想明白斜线的维护方式,也就是维护拐点斜率变化情况。怎么会降智这么严重呢?不知道。

Code
C++
#define FileIO
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define fi first
#define se second
#define il inline
bool stMem; double stT=clock();
const int N=2e5+10;
const ll P=998244353, M=1e9;
il ll qp(ll a,ll b=P-2){
	ll res=1;
	for(;b;b>>=1,a=(a*a)%P) if(b&1) res=(res*a)%P;
	return res;
}
// ---------------------------------------------------- //
int test_id;
ll n,l[N],r[N],L[N],R[N];
ll now_y, now_k, ans_x, ans_y;
vector<pair<ll,ll>> update_point;
il void upd(ll x,ll y){ /* cerr<<"-> ("<<x<<","<<y<<")\n"; */ if(y>ans_y) ans_y=y, ans_x=x;	}
il ll combine_seg(ll al,ll ar,ll bl,ll br){
	if(al<=bl&&br<=ar) return br-bl+1;
	if(bl<=al&&ar<=br) return ar-al+1;
	if(al>bl) swap(al,bl), swap(ar,br);
	if(ar<bl) return 0;
	return ar-bl+1;
}
il ll get_y(ll x){ ll su=0; for(int i=1;i<=n;++i) su+=combine_seg(l[i]+x,r[i]+x,L[i],R[i]); return su; }
// ---------------------------------------------------- //
il void solve(){
	cin>>n; 
	ans_x=-1e10, ans_y=-1e10;
	now_y=0;
	now_k=0;
	update_point.clear();
	for(int i=1;i<=n;++i)
		cin>>l[i]>>r[i]>>L[i]>>R[i];
//	for(int i=-5;i<=5;++i)
//		cerr<<"("<<i<<", "<<get_y(i)<<"), \n";
	for(int i=1;i<=n;++i){ // 维护每个点的函数增量值
		ll l_bottom=L[i]-r[i], r_bottom=R[i]-l[i];
		ll l_top=L[i]-l[i], r_top=R[i]-r[i];
		if(l_top>r_top) swap(l_top,r_top);
		if(l_bottom>r_bottom) swap(l_bottom,r_bottom);
//		cerr<<"rect on "<<l_bottom<<" ~ "<<l_top<<" ~ "<<r_top<<" ~ "<<r_bottom<<"\n";
		update_point.push_back({l_bottom-1,+1});
		update_point.push_back({l_top,-1});
		update_point.push_back({r_top,-1});
		update_point.push_back({r_bottom+1,+1});
	}
	sort(update_point.begin(),update_point.end());
	ll last_x=-1e10;
	for(auto val:update_point){
		ll x=val.fi, k_delta=val.se;
		now_y+=now_k*(x-last_x);
		upd(x,now_y);
		now_k+=k_delta;
		last_x=x;
	}
	cout<<ans_y<<" "<<ans_x<<"\n";
	return;
}
// ---------------------------------------------------- //
bool edMem;
int main(){
	#ifdef FileIO
		freopen("shift.in","r",stdin);
		freopen("shift.out","w",stdout);
	#endif
	ios::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
	int T=1; cin>>test_id>>T;
	while(T--) solve();
	cerr<<"\n";
	cerr<<"[Info] End Of Running. \n";
	cerr<<"       Time Used   : "<<(clock()-stT)/CLOCKS_PER_SEC*1000.00<<" ms\n";
	cerr<<"       Memory Used : "<<(&stMem-&edMem)/1048576.00<<" Mib\n";
	return 0;
}


原文