-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path2D_Prefix_Sum.cpp
59 lines (49 loc) · 1.35 KB
/
2D_Prefix_Sum.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include <bits/stdc++.h>
using namespace std;
/*
The general formula for 2D prefix sum at index (i,j):
psum[i][j] = psum[i-1][j] + psum[i][j-1] -
psum[i-1][j-1] + a[i][j]
*/
/*
Encountered in:
Forest Quries :CSES
Triptastic :CodeChef (https://www.codechef.com/problems/TRPTSTIC)
*/
// Implementation :
#define R 4
#define C 5
void prefixSum2D(int a[][C])
{
int psa[R][C];
psa[0][0] = a[0][0];
// Filling first row and first column
for (int i = 1; i < C; i++)
psa[0][i] = psa[0][i - 1] + a[0][i];
for (int i = 1; i < R; i++)
psa[i][0] = psa[i - 1][0] + a[i][0];
// updating the values in the cells
// as per the general formula
for (int i = 1; i < R; i++) {
for (int j = 1; j < C; j++)
// values in the cells of new
// array are updated
psa[i][j] = psa[i - 1][j] + psa[i][j - 1]
- psa[i - 1][j - 1] + a[i][j];
}
// displaying the values of the new array
for (int i = 0; i < R; i++) {
for (int j = 0; j < C; j++)
cout << psa[i][j] << " ";
cout << "\n";
}
}
int main()
{
int a[R][C] = { { 1, 1, 1, 1, 1 },
{ 1, 1, 1, 1, 1 },
{ 1, 1, 1, 1, 1 },
{ 1, 1, 1, 1, 1 } };
prefixSum2D(a);
return 0;
}