二维前缀和思想 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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值