[Hacker Rank] Ema`s Supercomputer

Ema’s Supercomputer

  • Time : O(n^2 m^2 min(n,m))
  • Space : O(nm)
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
int query(vector<string> grid) {
int n = grid.size(), m = grid[0].length();
int psum[16][16][4] = {};
for(int i = 0; i < n; i++) {
int l = 0, r = m - 1;
while(r >= 0) {
if(grid[i][l] == 'G') {
psum[i][l][0] = 1 + (l ? psum[i][l-1][0] : 0);
}
if(grid[i][r] == 'G') {
psum[i][r][1] = 1 + (r + 1 != m ? psum[i][r + 1][1] : 0);
}
l++,r--;
}
}

for(int i = 0; i < m; i++) {
int u = 0, b = n - 1;
while(b >= 0) {
if(grid[b][i] == 'G') {
psum[b][i][2] = 1 + (b + 1 != n ? psum[b + 1][i][2] : 0);
}
if(grid[u][i] == 'G') {
psum[u][i][3] = 1 + (u ? psum[u-1][i][3] : 0);
}
u++,b--;
}
}

int res = 0;
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
int l = INT_MAX;
for(int k = 0; k < 4; k++) l = min(l, psum[i][j][k]);
int area = l * 4 - 3;
res = max(res, area);
}
}

return res;
}

int twoPluses(vector<string> grid) {
int n = grid.size(), m = grid[0].length();
int psum[16][16][4] = {};
for(int i = 0; i < n; i++) {
int l = 0, r = m - 1;
while(r >= 0) {
if(grid[i][l] == 'G') {
psum[i][l][0] = 1 + (l ? psum[i][l-1][0] : 0);
}
if(grid[i][r] == 'G') {
psum[i][r][1] = 1 + (r + 1 != m ? psum[i][r + 1][1] : 0);
}
l++,r--;
}
}

for(int i = 0; i < m; i++) {
int u = 0, b = n - 1;
while(b >= 0) {
if(grid[b][i] == 'G') {
psum[b][i][2] = 1 + (b + 1 != n ? psum[b + 1][i][2] : 0);
}
if(grid[u][i] == 'G') {
psum[u][i][3] = 1 + (u ? psum[u-1][i][3] : 0);
}
u++,b--;
}
}

int res = 0, dy[4]{-1,0,1,0}, dx[4]{0,1,0,-1};
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
if(grid[i][j] != 'G') continue;
int len = INT_MAX;
for(int k = 0; k < 4; k++) len = min(len, psum[i][j][k]);
auto cp = grid;
for(int l = 0; l < len; l++) {
for(int k = 0; k < 4; k++) {
cp[i + dy[k]*l][j + dx[k]*l] = 'B';
}
int area = l * 4 + 1;
res = max(res, area * query(cp));
}
}
}

return res;
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/14/PS/HackerRank/two-pluses/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.