LOJ#3083. 「GXOI / GZOI2019」与或和(单调栈)
题面
题解
按位考虑贡献,如果\(mp[i][j]\)这一位为\(1\)就设为\(1\)否则设为\(0\),对\(or\)的贡献就是全为\(1\)的子矩阵个数,对\(and\)的贡献就是总矩阵个数减去全为\(0\)的子矩阵个数,单调栈搞一搞就好了
//minamoto
#include<bits/stdc++.h>
#define R register
#define inline __inline__ __attribute__((always_inline))
#define fp(i,a,b) for(R int i=(a),I=(b)+1;i<I;++i)
#define fd(i,a,b) for(R int i=(a),I=(b)-1;i>I;--i)
#define go(u) for(int i=head[u],v=e[i].v;i;i=e[i].nx,v=e[i].v)
template<class T>inline bool cmax(T&a,const T&b){return a<b?a=b,1:0;}
using namespace std;
char buf[1<<21],*p1=buf,*p2=buf;
inline char getc(){return p1==p2&&(p2=(p1=buf)+fread(buf,1,1<<21,stdin),p1==p2)?EOF:*p1++;}
int read(){
R int res,f=1;R char ch;
while((ch=getc())>'9'||ch<'0')(ch=='-')&&(f=-1);
for(res=ch-'0';(ch=getc())>='0'&&ch<='9';res=res*10+ch-'0');
return res*f;
}
const int N=1005,P=1e9+7;
inline int add(R int x,R int y){return x+y>=P?x+y-P:x+y;}
inline int dec(R int x,R int y){return x-y<0?x-y+P:x-y;}
inline int mul(R int x,R int y){return 1ll*x*y-1ll*x*y/P*P;}
int ksm(R int x,R int y){
R int res=1;
for(;y;y>>=1,x=mul(x,x))(y&1)?res=mul(res,x):0;
return res;
}
int a[N][N],st[N],c[N],b[N][N],bin[35],resor,resand,n,mx,top,sum;bool mp[N][N];
int calc(int id,int k){
int res=0,now,cc;
fp(i,1,n)fp(j,1,n)mp[i][j]=((a[i][j]>>id&1)==k);
fp(i,1,n){
fp(j,1,n)b[i][j]=(mp[i][j]?b[i-1][j]+1:0);
top=0,now=0;
fp(j,1,n){
cc=0;
while(top&&st[top]>=b[i][j])now-=c[top]*st[top],cc+=c[top],--top;
st[++top]=b[i][j],c[top]=cc+1,now+=st[top]*c[top],res=add(res,now);
}
}
return res;
}
int main(){
// freopen("testdata.in","r",stdin);
n=read(),sum=(1ll*n*(n+1)*n*(n+1)>>2)%P;
fp(i,1,n)fp(j,1,n)a[i][j]=read(),cmax(mx,a[i][j]);
mx=log2(mx);bin[0]=1;fp(i,1,mx)bin[i]=mul(bin[i-1],2);
fp(i,0,mx)resand=add(resand,mul(calc(i,1),bin[i]));
fp(i,0,mx)resor=add(resor,mul(dec(sum,calc(i,0)),bin[i]));
printf("%d %d\n",resand,resor);
return 0;
}
深深地明白自己的弱小