def main():
import sys
input = sys.stdin.read().split()
idx = 0
H, W = int(input[idx]), int(input[idx+1])
idx +=2
grid = []
for _ in range(H):
row = list(map(int, input[idx:idx+W]))
idx += W
grid.append(row)
# dp[i][j] represents the maximum sum up to the i-th row, considering the j-th column's selection
# We use two arrays to represent the previous and current row's states
prev = [-1] * W
curr = [-1] * W
# Initialize the first row
dp_row = [0] * (W + 1)
for j in range(1, W + 1):
# For the first row, we can either take the current cell or not
if j == 1:
dp_row[j] = grid[0][j-1]
else:
dp_row[j] = max(dp_row[j-1], dp_row[j-2] + grid[0][j-1])
for j in range(W):
curr[j] = dp_row[j+1]
prev, curr = curr, [-1] * W
for i in range(1, H):
# Compute the current row's maximum sum when not considering the previous row
dp_current = [0] * (W + 1)
for j in range(1, W + 1):
if j == 1:
dp_current[j] = grid[i][j-1]
else:
dp_current[j] = max(dp_current[j-1], dp_current[j-2] + grid[i][j-1])
# Now consider the previous row's constraints
new_curr = [0] * W
for j in range(W):
# The current row's j-th column can be selected only if the previous row's j-1, j, j+1 are not selected
max_prev = 0
for k in range(W):
if abs(k - j) > 1:
if prev[k] > max_prev:
max_prev = prev[k]
new_curr[j] = dp_current[j+1] + max_prev
curr = new_prev
prev, curr = curr, [0]*W
print(max(prev))
if __name__ == "__main__":
main()
However, this code is incomplete and may not work correctly. The correct approach requires a more sophisticated dynamic programming method. The actual solution involves processing each row's valid states and ensuring compatibility with the previous row's states. The following code is a correct implementation:
python
def main():
import sys
input = sys.stdin.read().split()
idx = 0
H, W = int(input[idx]), int(input[idx+1])
idx += 2
grid = []
for _ in range(H):
grid.append(list(map(int, input[idx:idx+W])))
idx += W
prev = [0]*(1<<W)
for mask in range(1<<W):
valid = True
sum_ = 0
for j in range(W):
if (mask >> j) & 1:
if j > 0 and (mask >> (j-1)) & 1:
valid = False
sum_ += grid[0][j]
if valid:
prev[mask] = sum_
else:
prev[mask] = -1
for i in range(1, H):
curr = [0]*(1<<W)
for curr_mask in range(1<<W):
valid = True
sum_ = 0
for j in range(W):
if (curr_mask >> j) & 1:
if j > 0 and (curr_mask >> (j-1)) & 1:
valid = False
sum_ += grid[i][j]
if not valid:
curr[curr_mask] = -1
continue
max_prev = 0
for prev_mask in range(1<<W):
if prev[prev_mask] == -1:
continue
conflict = False
for j in range(W):
if (curr_mask >> j) & 1 and (prev_mask & (1 << j)) != 0:
conflict = True
break
if not conflict:
max_prev = max(max_prev, prev[prev_mask])
curr[curr_mask] = sum_ + max_prev
prev = curr
print(max(prev))
if __name__ == "__main__":
main()
However, this code is not feasible for W=200 because the number of masks is 2^200, which is way too large. Thus, the correct approach is to use a more efficient dynamic programming method that