二維前綴和思想 Codeforces Good Bye 2015 C題 New Year and Domino

New Year and Domino

They say “years are like dominoes, tumbling one after the other”. But would a year fit into a grid? I don’t think so.

Limak is a little polar bear who loves to play. He has recently got a rectangular grid with h rows and w columns. Each cell is a square, either empty (denoted by ‘.’) or forbidden (denoted by ‘#’). Rows are numbered 1 through h from top to bottom. Columns are numbered 1 through w from left to right.

Also, Limak has a single domino. He wants to put it somewhere in a grid. A domino will occupy exactly two adjacent cells, located either in one row or in one column. Both adjacent cells must be empty and must be inside a grid.

Limak needs more fun and thus he is going to consider some queries. In each query he chooses some rectangle and wonders, how many way are there to put a single domino inside of the chosen rectangle?


題目大意:先給你一個長方形的圖,圖有 h*w 個方塊,每個方塊要不是空 ,要不被佔,然後問你在一個子圖裏面兩個連續的空方塊有多少種連接方式;

二維前綴和很容易想到,但是沒想到要橫豎分開表示,sumr[][] 表示橫着擺的個數,sumc[][] 表示豎着擺的個數;

然後求答案要注意不是一般的二維前綴和求和,要注意邊界上的加減問題,畫個圖就非常明顯了;

代碼:

#include<bits/stdc++.h>
#define LL long long
#define pa pair<int,int>
#define ls k<<1
#define rs k<<1|1
#define inf 0x3f3f3f3f
using namespace std;
const int N=100100;
const int M=2000100;
const LL mod=1e9+7;
char s[510][510];
LL sumr[510][510],sumc[510][510];
int main(){
	int h,w;cin>>h>>w;
	for(int i=1;i<=h;i++) scanf("%s",s[i]+1);
	for(int i=1;i<=h;i++){
		for(int j=1;j<=w;j++){
			sumr[i][j]=sumr[i][j-1]+sumr[i-1][j]-sumr[i-1][j-1];
			sumc[i][j]=sumc[i][j-1]+sumc[i-1][j]-sumc[i-1][j-1];
			if(s[i][j]=='.'){
				if(s[i][j-1]=='.') sumr[i][j]++;
				if(s[i-1][j]=='.') sumc[i][j]++;
			}
		}
	}
	int q;cin>>q;
	while(q--){
		int r1,c1,r2,c2;
		scanf("%d%d%d%d",&r1,&c1,&r2,&c2);
		LL ans=sumr[r2][c2]-sumr[r1-1][c2]-sumr[r2][c1]+sumr[r1-1][c1];
		ans+=sumc[r2][c2]-sumc[r1][c2]-sumc[r2][c1-1]+sumc[r1][c1-1];
		printf("%lld\n",ans);
	}
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章