-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcount_square_submatrices.cpp
More file actions
61 lines (57 loc) · 1.72 KB
/
Copy pathcount_square_submatrices.cpp
File metadata and controls
61 lines (57 loc) · 1.72 KB
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
60
61
#include <algorithm>
#include <iostream>
#include <vector>
#include <cstring>
using namespace std;
class Solution {
typedef unsigned long long ull;
public:
int countSquares(vector<vector<int>>& matrix) {
int rows = matrix.size(), cols = matrix[0].size();
vector<vector<ull>> dp(matrix.size(), vector<ull>(matrix[0].size()));
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
int d = (i > 0 && j > 0 ? dp[i - 1][j - 1] : 0);
int l = j > 0 ? dp[i][j - 1]: 0;
int r = i > 0 ? dp[i - 1][j]: 0;
dp[i][j] = l + r + matrix[i][j] - d;
}
}
int ans = 0;
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
int k = 1;
if (matrix[i][j])
++ans;
int base = i > 0 && j > 0 ? dp[i - 1][j - 1] : 0;
while (k + i < rows && k + j < cols) {
int top = i > 0 ? dp[i - 1][j + k]: 0;
int left = j > 0 ? dp[i + k][j - 1]: 0;
if ((k + 1)*(k+ 1) == (dp[k+ i][k+j] + base - top - left))
++ans;
++k;
}
}
}
return ans;
}
};
static auto fastio = [](){
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
std::cout.tie(nullptr);
return nullptr;
}();
int main() {
Solution solution;
int n, m;
cin >> n >> m;
vector<vector<int>> v(n, vector<int>(m));
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
cin >> v[i][j];
}
}
cout << solution.countSquares(v);
return 0;
}