版本比较
题解:CF611C New Year and Domino
正文
增加 59 行删除 56 行
18 行未改动192021222324252426272829307 行未改动38394041404142434442434445464748495051525354535455565758565758596061626063646263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810610918 行未改动垂直骨牌:记录在上端点位置 (i,j),下端点在 (i+1,j)
2. 前缀和数组定义三个二维前缀和数组:c[N][N], d[N][N], b[N][N];
3. 查询处理4. 查询处理对于查询矩形 (r1,c1) 到 (r2,c2):
第一步:计算完全在矩形内的骨牌我们可以用前缀和快速计算7 行未改动垂直骨牌跨越下边界:上端点在 (r2, c1..c2),下端点在 (r2+1, c1..c2)
注意:不需要考虑左边界和上边界,因为如果骨牌跨越这些边界,它根本不会被包含在查询矩形的任何前缀和中。
第三步:最终计算公式text答案 = all_hor + all_ver - (矩形右边界上的水平骨牌数量) - (矩形下边界上的垂直骨牌数量)第三步:最终计算公式:
b[x2][y2]-b[x1-1][y2]-b[x2][y1-1]+b[x1-1][y1-1] - c[x2][y2]-c[x2][y1-1] - d[x2][y2]-d[x1-1][y2];
其中:
矩形右边界上的水平骨牌数量 = 查询 (r1,c2) 到 (r2,c2) 中的水平骨牌(但要求 c2 < w)
矩形下边界上的垂直骨牌数量 = 查询 (r2,c1) 到 (r2,c2) 中的垂直骨牌(但要求 r2 < h)
代码演示:
#include <bits/stdc++.h>using namespace std; #include <bits/stdc++.h> using namespace std;
const int N = 5e2+5;int h, w, q, b[N][N], c[N][N], d[N][N];char a[N][N]; const int N = 5e2+5; int h, w, q, b[N][N], c[N][N], d[N][N]; char a[N][N];
int main(){ int main(){
ios::sync_with_stdio(0); cin.tie(0),cout.tie(0); cin >> h >> w; for(int i = 1; i <= h; i++){ for(int j = 1; j <= w; j++){ cin >> a[i][j]; } } for(int i = 1; i <= h; i++){ for(int j = 1; j <= w; j++){ if(a[i][j] == '.'){ if(a[i+1][j] == '.'){ c[i][j]++; } if(a[i][j+1] == '.'){ d[i][j]++; } } } } for(int i = 1; i <= h; i++){ for(int j = 1; j <= w; j++){ b[i][j] = b[i-1][j]+b[i][j-1]+c[i][j]+d[i][j]-b[i-1][j-1]; } } for(int i = 1; i <= h; i++){ for(int j = 1; j <= w; j++){ c[i][j] += c[i][j-1]; } } for(int j = 1; j <= w; j++){ for(int i = 1; i <= h; i++){ d[i][j] += d[i-1][j]; } } cin >> q; for(int i = 1, x1, x2, y1, y2; i <= q; i++){ cin >> x1 >> y1 >> x2 >> y2; int cnt = b[x2][y2]-b[x1-1][y2]-b[x2][y1-1]+b[x1-1][y1-1]; int ans = c[x2][y2]-c[x2][y1-1]; int tmp = d[x2][y2]-d[x1-1][y2]; cout << cnt-ans-tmp << "\n"; } ios::sync_with_stdio(0); cin.tie(0),cout.tie(0); cin >> h >> w; for(int i = 1; i <= h; i++){ for(int j = 1; j <= w; j++){ cin >> a[i][j]; } } for(int i = 1; i <= h; i++){ for(int j = 1; j <= w; j++){ if(a[i][j] == '.'){ if(a[i+1][j] == '.'){ c[i][j]++; } if(a[i][j+1] == '.'){ d[i][j]++; } } } } for(int i = 1; i <= h; i++){ for(int j = 1; j <= w; j++){ b[i][j] = b[i-1][j]+b[i][j-1]+c[i][j]+d[i][j]-b[i-1][j-1]; } } for(int i = 1; i <= h; i++){ for(int j = 1; j <= w; j++){ c[i][j] += c[i][j-1]; } } for(int j = 1; j <= w; j++){ for(int i = 1; i <= h; i++){ d[i][j] += d[i-1][j]; } } cin >> q; for(int i = 1, x1, x2, y1, y2; i <= q; i++){ cin >> x1 >> y1 >> x2 >> y2; int cnt = b[x2][y2]-b[x1-1][y2]-b[x2][y1-1]+b[x1-1][y1-1]; int ans = c[x2][y2]-c[x2][y1-1]; int tmp = d[x2][y2]-d[x1-1][y2]; cout << cnt-ans-tmp << "\n"; } return 0;} }