跳到正文

题解

奇妙的二分做法/SCP-S 2025T1题解

Bocchi_Offical约 3 分钟
原文
文章信息与版本

文章信息

发布
2025年10月23日
收录
2025年12月12日
更新
2026年11月13日
篇幅
约 3 分钟
题目
P14253

版本

  1. v2当前
  2. v1

鸣谢:@langlang_

(给我提供了一部分灵感,虽然他也有一种方法)

提供一种奇妙的二分做法。

注意到题目中 rr 端点取得最右,答案不严格更优(至少不会更劣),所以我们只需要求当前 ll 对应的 00 的基准值在 ll 至 nn 区间内有多少个对应的 00 的基准值就对了。

我们只需要用一个 map 来存储前缀和数组信息,将符合的端点加入 vector,二分左端点即可。

C++
#include<bits/stdc++.h>
#define int long long
using namespace std;
int t;
int n;
int a[1000005];
int sum[1000005];
unordered_map<int,vector<int> > mp;
int ans;
signed main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
	cin>>t;
	while(t--)
	{
		memset(sum,0,sizeof sum);
        mp.clear();
		ans=0;
		cin>>n;
		for(int i=1;i<=n;i++)
		{
			cin>>a[i];
		}
		for(int i=1;i<=n;i++)
		{
			sum[i]=sum[i-1]+a[i];
            mp[sum[i]].push_back(i);
		}
		for(int i=1;i<=n;i++)
		{
			int pivot0=sum[i]-a[i];
            if(mp[pivot0].empty()) continue;
            int l=0;
            int r=mp[pivot0].size()-1;
            while(l<=r)
            {
                int mid=(l+r)>>1;
                if(mp[pivot0][mid]>=i)
                {
                    r=mid-1;
                }
                else
                {
                    l=mid+1;
                }
            }
            ans=max(ans,(long long)mp[pivot0].size()-l);
		}
		cout<<ans<<'\n';
	}
}

AC 记录

原文