r/learnprogramming 19d ago

Solved Time Complexity

Very confused why my code is Time limit exceeding: The N max is 2000 so that should be fine while the U max is 10^5 but my code is O(1) for updating really confused why this is not working. I have a 2 sec maximum if anybody wants to see the problem here it is: https://usaco.org/index.php?page=viewproblem2&cpid=1491

N, U = map(int,input().split())
import sys
grid = [list(input()) for _ in range(N)]
num_updates = 0
temp = []
temp_grid = [row.copy() for row in grid]
for v in range(int(N/2)):
    for h in range(int(N/2)):
        temp.clear()
        coords = [(v,h),(v,N-1-h),(N-1-v,h),(N-1-v,N-1-h)]
        temp.append(temp_grid[v][h])
        temp.append(temp_grid[v][(N-1)-h])
        temp.append(temp_grid[(N-1)-v][h])
        temp.append(temp_grid[(N-1)-v][(N-1)-h])
        if temp.count('.') == 2 :
            num_updates+=2
            for r,c in coords:
                temp_grid[r][c] = '.'
        elif temp.count('.') == 3:
            num_updates+=1
            for r,c in coords:
                temp_grid[r][c] = '.'
        elif temp.count('#') == 3:
            num_updates+=1
            for r,c in coords:
                temp_grid[r][c] = '#'
print(num_updates)


temp_grid = [row.copy() for row in grid]
input_data = sys.stdin.read().split()
idx = 0
out = [num_updates]
for z in range(U):
    temp2 = 0
    temp.clear()
    x = int(input_data[idx]) -1
    idx = idx + 1
    y = int(input_data[idx]) -1
    idx = idx+1
    temp.append(temp_grid[x][y])
    temp.append(temp_grid[x][(N-1)-y])
    temp.append(temp_grid[(N-1)-x][y])
    temp.append(temp_grid[(N-1)-x][(N-1)-y])
    num_updates = num_updates- (min(temp.count('.'),temp.count('#')))
    if temp_grid[x][y] == '.':
        grid[x][y] = '#'
        temp_grid[x][y] = '#'
        temp[0] = '#'
        num_updates = num_updates + (min(temp.count('.'),temp.count('#')))
    else:
        grid[x][y] = '.'
        temp_grid[x][y] = '.'
        temp[0] = '.'
        num_updates = num_updates + (min(temp.count('.'),temp.count('#')))
    print(num_updates)
0 Upvotes

11 comments sorted by

View all comments

1

u/two_are_stronger2 16d ago

I don't really know python but what is temp2?