Binary Differences
https://csacademy.com/contest/archive/task/binary-differences
n个数,只有0和1,求所有子区间价值不相同的有多少中,价值是0的个数-1的个数
解法:0的贡献是1,1的贡献是-1,求出贡献的前缀和为s[i],利用上一个区间[l,r]求出当前区间[sum-r,sum-l],同时更新最大范围
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
//#pragma comment(linker, "/stack:200000000") //#pragma GCC optimize("Ofast,no-stack-protector") //#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native") //#pragma GCC optimize("unroll-loops") #include<bits/stdc++.h> #define fi first #define se second #define mp make_pair #define pb push_back #define pi acos(-1.0) #define ll long long #define mod 1000000007 #define C 0.5772156649 #define ls l,m,rt<<1 #define rs m+1,r,rt<<1|1 #define pil pair<int,ll> #define pii pair<int,int> #define ull unsigned long long #define base 1000000000000000000 #define fio ios::sync_with_stdio(false);cin.tie(0) using namespace std; const double g=10.0,eps=1e-12; const int N=100000+10,maxn=100000+10,inf=0x3f3f3f3f,INF=0x3f3f3f3f3f3f3f3f; int a[N]; int main() { int n,sum=0; scanf("%d",&n); int l,r,tel,ter; l=r=tel=ter=0; for(int i=1;i<=n;i++) { scanf("%d",&a[i]); if(a[i])sum--; else sum++; l=min(l,sum-ter); r=max(r,sum-tel); tel=min(tel,sum); ter=max(ter,sum); } printf("%d\n",r-l+1); return 0; } /******************** ********************/