Old Macdonald wants to build a new hen house for his hens. He buys a new rectangular area of size N by M. The night before he builds the hen house, snake Rana devises an evil plan to plant bombs in K distinct cells in the area to kill the hens and eat them for dinner later.
The morning of, Old Macdonald notices that each of the K cells, where snake Rana planted a bomb, have a marking on them. That won’t stop him though, all he must do is build the hen house in an area with no bombs.
Assume that rows are numbered from top to bottom, and columns are numbered from left to right. Old Macdonald now wants to know the number of ways he can choose sub-rectangles of top left coordinates (x1, y1) and bottom right coordinates (x2, y2) (x1 ≤ x2) (y1 ≤ y2)such that there are no bombs in the sub rectangle.
The first line of input is T – the number of test cases.
The first line of each test case is three integers N, M, and K (1 ≤ N, M ≤ 104) (1 ≤ K ≤ 20).
The next K lines each contains distinct pair of integers x, y (1 ≤ x ≤ N) (1 ≤ y ≤ M) - where (x, y) is the coordinate of the bomb.
For each test case, output a line containing a single integer - the number of sub-rectangles that don’t contain any bombs.
3 2 2 1 2 2 6 6 2 5 2 2 5 10000 10000 1 1 1
5 257 2500499925000000
此题利用容斥思想,最重要的是一个两个推导关系,一个n*m的矩形一共有C(n+1,2)*C(m+1,2)个不同的矩形,这是一个关系,还有一个关系是在这个大的矩形里面必须包含某个正方形的矩形的个数为四个宽度加1想乘,这个便是结果,然后下面就可以利用容斥的思想了。
代码:
#include<bits/stdc++.h>
using namespace std;
#define inf 0x3f3f3f3f
long long C(long long n,long long k)
{
if(n-k<k)
k=n-k;
long long ans=1;
for(int i=1; i<=k; i++)
{
ans=ans*(n-i+1)/i;
}
return ans;
}
const int maxn=30;
struct qq
{
long long x,y;
} q[maxn];
int k;
long long n,m;
long long solve(int x)
{
long long zsx=inf,zsy=inf,yxx=-1,yxy=-1;
int sum=0;
for(int i=0; i<k; i++)
{
if(x&(1<<i))
{
sum++;
zsx=min(zsx,q[i].x-1);
zsy=min(zsy,q[i].y-1);
yxx=max(yxx,q[i].x);
yxy=max(yxy,q[i].y);
}
}
long long res=(zsx+1)*(zsy+1)*(n-yxx+1)*(m-yxy+1);
if(sum&1)
{
return -res;
}
else return res;
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
scanf("%I64d%I64d%d",&n,&m,&k);
for(int i=0; i<k; i++)
{
scanf("%I64d%I64d",&q[i].x,&q[i].y);
}
long long sum=C(n+1,2)*C(m+1,2);
// printf("%I64d\n",sum);
for(int i=1; i<(1<<k); i++)
{
sum+=solve(i);
}
printf("%I64d\n",sum);
}
}