并不对劲的loj3083:p5300:[GXOI/GZOI2019]与或和

题目大意

有一个\(n*n\)的矩阵
\(a_{1,1},...,a_{1,n}\)
\(a_{2,1},...,a_{2,n}\)
\(...\)
\(a_{n,1},...,a_{n,n}\)
求它所有子矩阵的矩阵内所有数的与和之和、所有子矩阵的矩阵内所有数的或和之和。
\(n\leq 1000;a<2^31;\)

题解

先求与和,按二进制位考虑与和当前位为1的子矩阵数。
这相当于求矩阵内所有数都满足当前位为1的子矩阵数。
或和同理,求总子矩阵数减矩阵内所有数当前位为0的子矩阵数。

代码
#include<algorithm>
#include<cmath>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<ctime>
#include<iomanip>
#include<iostream>
#include<map>
#include<queue>
#include<set>
#include<stack>
#include<vector>
#define rep(i,x,y) for(register int i=(x);i<=(y);++i)
#define dwn(i,x,y) for(register int i=(x);i>=(y);--i)
#define view(u,k) for(int k=fir[u];~k;k=nxt[k])
#define maxn 10007
#define LL long long
using namespace std;
int read()
{
	int x=0,f=1;char ch=getchar();
	while(!isdigit(ch)&&ch!='-')ch=getchar();
	if(ch=='-')f=-1,ch=getchar();
	while(isdigit(ch))x=(x<<1)+(x<<3)+ch-'0',ch=getchar();
	return x*f;
}
void write(int x)
{
	if(x==0){putchar('0'),putchar(' ');return;}
	int f=0;char ch[20];
	if(x<0)putchar('-'),x=-x;
	while(x)ch[++f]=x%10+'0',x/=10;
	while(f)putchar(ch[f--]);
	putchar(' ');
	return;
}
const int mod=1e9+7;
int inv2,n,a[maxn][maxn],b[maxn][maxn],ans,stk[maxn],tp,sum;
int mul(int x,int y){int res=1;while(y){if(y&1)res=(LL)res*x%mod;x=(LL)x*x%mod,y>>=1;}return res;}
int mo(int x){return x>=mod?x-mod:x;}
void work(int typ)
{
	rep(x,0,30)
	{
		int k=(1<<x);
		dwn(i,n,1)rep(j,1,n)
		{
			if((a[i][j]&k)!=k*typ)b[i][j]=0;
			else if(i==n||((a[i+1][j]&k)!=k*typ))b[i][j]=1;
			else b[i][j]=b[i+1][j]+1;
		}
		int now=0,num=0;stk[0]=n+1;
		rep(i,1,n)
		{
			tp=now=0;
			dwn(j,n,1)
			{
				while(tp&&b[i][stk[tp]]>=b[i][j])now=mo(now-(LL)b[i][stk[tp]]*(stk[tp-1]-stk[tp])%mod+mod),tp--;
				stk[++tp]=j;now=mo(now+(LL)b[i][j]*(stk[tp-1]-j)%mod);num=mo(num+now);
			}
		}
		if(typ==0)num=mo(sum-num+mod);
		ans=mo(ans+(LL)k*num%mod);
	}
}
int main()
{
	n=read(),inv2=mul(2,mod-2);sum=mo((LL)n*(n-1)%mod*inv2%mod+n);sum=(LL)sum*sum%mod;
	rep(i,1,n)rep(j,1,n)a[i][j]=read();
	work(1);
	write(ans),ans=0;
	work(0);
	write(ans);
	return 0;
}
posted @ 2020-06-08 19:37  echo6342  阅读(127)  评论(0编辑  收藏  举报