Gym - 101350G Snake Rana
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.
Input
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.
Output
For each test case, output a line containing a single integer - the number of sub-rectangles that don’t contain any bombs.
Example Input
3
2 2 1
2 2
6 6 2
5 2
2 5
10000 10000 1
1 1
Output
5
257
2500499925000000
题意:
N*M
大小的矩阵中,有K
个地雷,求不含有地雷的所有矩形的总数。
思路:
容斥原理。主要考虑K
的范围,然后用20尾的2进制数表示是否选择当前序号的地雷。根据容斥原理,减去奇数个雷的情况,加上偶数个雷的情况。容斥原理通常用于计数情况。
#include <algorithm>
#include <iostream>
#include <fstream>
#include <cstring>
#include <cstdlib>
#include <vector>
#include <cstdio>
#include <bitset>
#include <string>
#include <cmath>
#include <ctime>
#include <queue>
#include <stack>
#include <list>
#include <map>
#include <set>
using namespace std;
const int maxn=1e4+100;
const int INF=1e6+100;
int pointx[maxn];
int pointy[maxn];
int main(){
int T;
scanf("%d",&T);
while(T--){
int n,m,k;
scanf ("%d%d%d",&n,&m,&k);
memset(pointx,0,sizeof(pointx));
memset(pointy,0,sizeof(pointy));
for(int i=0;i<k;i++){
scanf("%d%d",&pointx[i],&pointy[i]);
}
long long ans=(n*1LL*(n+1))/2*(m*1LL*(m+1))/2;//注意强制转换LL
for(int i=1;i<(1<<k);i++){//1~2^20-1,1表示选择该位置的雷,0表示不选择
int t=i;
int cnt=0;
while(t){
if(t&1){
cnt++;
}
t>>=1;
}//cnt记录选择了几个雷
int lx=INF,ly=INF,rx=0,ry=0;
for(int j=0;j<k;j++){
if((1<<j) & i){
lx=min(lx,pointx[j]);
ly=min(ly,pointy[j]);
rx=max(rx,pointx[j]);
ry=max(ry,pointy[j]);
}//选择包含这些点矩形的边际
}
long long cur=1LL*lx*ly*(n-rx+1)*(m-ry+1);//强制转换LL,wa了四发
if(cnt&1){//奇数时减去
ans-=cur;
}else{//偶数时补上
ans+=cur;
}
}
printf("%I64d\n",ans);
}
return 0;
}