三维前缀和

二维前缀和模板:

预处理:dp[i][j]=dp[i-1][j]+dp[i][j-1]-dp[i-1][j-1]+map[i][j];

查询:dp[x2][y2]+dp[x1-1][y1-1]-dp[x1-1][y2]-dp[x2][y1-1]

三维前缀和模板:

预处理:
pre[i][j][k]=mp[i][j][k]-pre[i-1][j-1][k]-pre[i-1][j][k-1]-pre[i][j-1][k-1]+pre[i][j][k-1]+pre[i][j-1][k]+pre[i-1][j][k]+pre[i-1][j-1][k-1];

查询:
res=pre[x2][y2][z2]-pre[x1][y2][z2]-pre[x2][y1][z2]-pre[x2][y2][z1]+pre[x1][y1][z2]+pre[x1][y2][z1]+pre[x2][y1][z1]-pre[x1][y1][z1];

三维前缀和模板题:
https://atcoder.jp/contests/abc366/tasks/abc366_d

#include<bits/stdc++.h>
#define endl '\n'
#define int long long
#define lowbit(x) (x&-x)
using namespace std;
const double pi=acos(-1);

void solve(){
	int n;cin>>n;
	vector<vector<vector<int>>> mp(n+1,vector<vector<int>>(n+1,vector<int>(n+1,0ll)));
	vector<vector<vector<int>>> pre(n+1,vector<vector<int>>(n+1,vector<int>(n+1,0ll)));
	for(int i=1;i<=n;i++){
		for(int j=1;j<=n;j++){
			for(int k=1;k<=n;k++){
				cin>>mp[i][j][k];
			}
		}
	}

	for(int i=1;i<=n;i++){
		for(int j=1;j<=n;j++){
			for(int k=1;k<=n;k++){
				pre[i][j][k]=mp[i][j][k]-pre[i-1][j-1][k]-pre[i-1][j][k-1]-pre[i][j-1][k-1]+pre[i][j][k-1]+pre[i][j-1][k]+pre[i-1][j][k]+pre[i-1][j-1][k-1];
			}
		}
	}


	int q;cin>>q;
	while(q--){
		int x1,x2,y1,y2,z1,z2;cin>>x1>>x2>>y1>>y2>>z1>>z2;
		x1--,y1--,z1--;
		int res=0;
		res=pre[x2][y2][z2]-pre[x1][y2][z2]-pre[x2][y1][z2]-pre[x2][y2][z1]+pre[x1][y1][z2]+pre[x1][y2][z1]+pre[x2][y1][z1]-pre[x1][y1][z1];
		cout<<res<<endl;
	}

}
signed main(){
	ios::sync_with_stdio(false); cin.tie(nullptr);
	int t=1;
	//cin>>t;
	while(t--) solve();
	return 0;
}

posted on 2024-10-14 21:47  TaopiTTT  阅读(6)  评论(0编辑  收藏  举报