原题
题意
一个n*n的格子,每一行和每一列都有且只有一个黑色格子。“美丽的矩形”定义为一个矩形的四个角中恰好有两个是黑色格子。
对于每次询问,给出一个矩形,查询至少包含给定矩形的一个格子的所有矩形中,“美丽的矩形”的个数。
(不懂的可以看Codeforces853C样例解释)。
解题思路
假设在n*n的区域中给出一个矩形,那么区域会被划分成以下9块,其中第5块表示给定矩形
1 | 2 | 3 |
4 | 5 | 6 |
7 | 8 | 9 |
假定我们用主席树求出了9块中每一块里面包含的黑色格子的个数,第i块内的黑色格子数目记为cnti。
对9块中每一块分别考虑。
对第1块而言,能和它组成“美丽的矩形”并符合要求的黑色格子一定在第5/6/8/9块中。
对第2块而言,能和它组成“美丽的矩形”并符合要求的黑色格子一定在第4/5/6/7/8/9块中。
……
对第5块而言,能和它组成“美丽的矩形”并符合要求的黑色格子一定是所有黑色格子,也就是(n-1)个格子。
……
假设我们把这些答案累加起来,会发现每个“美丽的矩形”被算了两次,因此答案需要/2。
代码
附上丑陋的代码……
#include <cstdio>
using namespace std;
typedef long long LL;
const int N=2e5+10,Node=N*20;
int n,q,root[N];
struct SegmentTree
{
int sum[Node],son[Node][2],node;
int newnode(int x)
{
++node;
sum[node]=sum[x];
son[node][0]=son[x][0];
son[node][1]=son[x][1];
return node;
}
void Insert(int &z,int x,int l,int r,int pos)
{
z=newnode(x); sum[z]++;
if (l==r) return ;
int mid=(l+r)>>1;
if (pos<=mid) Insert(son[z][0],son[x][0],l,mid,pos);
else Insert(son[z][1],son[x][1],mid+1,r,pos);
}
int Query(int rs,int ls,int l,int r,int ql,int qr)
{
if (ql>qr) return 0;
if (ql<=l && r<=qr) return sum[rs]-sum[ls];
int mid=(l+r)>>1,ret=0;
if (ql<=mid) ret+=Query(son[rs][0],son[ls][0],l,mid,ql,qr);
if (qr>mid) ret+=Query(son[rs][1],son[ls][1],mid+1,r,ql,qr);
return ret;
}
}St;
void Init()
{
scanf("%d%d",&n,&q);
int x;
for (int i=1;i<=n;++i)
{
scanf("%d",&x);
St.Insert(root[i],root[i-1],1,n,x);
}
}
void Solve()
{
int l,r,u,d;
for (int i=1;i<=q;++i)
{
scanf("%d%d%d%d",&l,&d,&r,&u);
int cnt1=St.Query(root[l-1],root[0],1,n,u+1,n);
int cnt2=St.Query(root[r],root[l-1],1,n,u+1,n);
int cnt3=St.Query(root[n],root[r],1,n,u+1,n);
int cnt4=St.Query(root[l-1],root[0],1,n,d,u);
int cnt5=St.Query(root[r],root[l-1],1,n,d,u);
int cnt6=St.Query(root[n],root[r],1,n,d,u);
int cnt7=St.Query(root[l-1],root[0],1,n,1,d-1);
int cnt8=St.Query(root[r],root[l-1],1,n,1,d-1);
int cnt9=St.Query(root[n],root[r],1,n,1,d-1);
LL ans=0;
ans+=1ll*cnt1*(cnt5+cnt6+cnt8+cnt9);
ans+=1ll*cnt2*(cnt4+cnt5+cnt6+cnt7+cnt8+cnt9);
ans+=1ll*cnt3*(cnt4+cnt5+cnt7+cnt8);
ans+=1ll*cnt4*(cnt2+cnt3+cnt5+cnt6+cnt8+cnt9);
ans+=1ll*cnt5*(n-1);
ans+=1ll*cnt6*(cnt1+cnt2+cnt4+cnt5+cnt7+cnt8);
ans+=1ll*cnt7*(cnt2+cnt3+cnt5+cnt6);
ans+=1ll*cnt8*(cnt1+cnt2+cnt3+cnt4+cnt5+cnt6);
ans+=1ll*cnt9*(cnt1+cnt2+cnt4+cnt5);
printf("%I64d\n",ans/2);
}
}
int main()
{
Init();
Solve();
return 0;
}