题解:P12894 [蓝桥杯 2025 国 Java B] 智能交通信号灯
思路
让我们思考一下这道题的突破口。
不难发现只有两个数的
当答案为
当答案为
当答案为
然后对于一个区间,我们思考怎么快速计算。
我们记当前区间内
那么接下来需要动用我们小学水平的组合数技巧。
分别求出不同答案的出现次数,然后就做完了。
在这里给出出现次数,令
答案为
答案为
答案为
维护
code
#include <bits/stdc++.h>
#define int long long
using namespace std;
const int N=1e5+5;
int n,m;
struct trary
{
#define lw (x&-x)
int c[N];
inline void update(int x,int y)
{
for(;x<=n;x+=lw)c[x]+=y;
return;
}
inline int query(int x)
{
int ans=0;
for(;x>=1;x-=lw)ans+=c[x];
return ans;
}
}subaru,momoka;
int a[N];
signed main()
{
ios::sync_with_stdio(false),cin.tie(nullptr),cout.tie(nullptr);
cin>>n>>m;
for(int i=1;i<=n;++i)
{
cin>>a[i];
subaru.update(i,a[i]==1);
momoka.update(i,a[i]==2);
}
for(int i=1;i<=m;++i)
{
int op,x,y;
cin>>op>>x>>y;
if(op==1)
{
int s1=subaru.query(y)-subaru.query(x-1);
int s2=momoka.query(y)-momoka.query(x-1);
cout<<3*s1*s2+s1*(s1-1)+2*s1*(y-x+1-s1-s2)+(y-x+1-s1)*(y-x-s1)/2<<'\n';
}
if(op==2)
{
if(a[x]==1)subaru.update(x,-1);
if(a[x]==2)momoka.update(x,-1);
a[x]=y;
if(a[x]==1)subaru.update(x,1);
if(a[x]==2)momoka.update(x,1);
}
}
return 0;
}