在输入量大的情况下,如何在4秒内执行此代码



注意:我不能使用任何非python内置的外部模块。

问题:

一位新的和即将到来的艺术家有一种独特的方式来创造方格图案。这个想法是使用M×N画布,该画布最初完全为黑色。然后艺术家反复选择一行或一列,并沿着该行或列运行它们的魔刷。笔刷发生变化行或列中每个单元格的颜色从黑色到金色或从金色到黑色。根据艺术家的选择,你的工作是确定图案中出现了多少黄金由这些选择决定。

输入规范

第一行输入为正整数M。第二行输入为正数整数N。第三行输入为正整数K。其余输入为K线给出了艺术家的选择。每一行后面都是R由一个空格,然后是一个整数,该整数是一个行号,或者C后跟一个空格然后是作为列编号的整数。行从1到M从上到下编号。列从左到右从1到N编号。

输出规格

输出一个非负整数,该整数等于图案由艺术家的选择决定。

限制

M和N可以达到5000 000

K可以高达1000 000

我的解决方案

import sys
raw_input = sys.stdin.readline
m = int(raw_input())
n = int(raw_input())
brushes = raw_input()
stroke = []

colors = [['B' for _ in range(n)] for _ in range(m)]
for i in range(int(brushes)):
g = raw_input().split(' ')
if stroke.count(g) == 1:
stroke.remove(g)
else:
stroke.append(g)
def changeColumn(num,colors,index):
if num == 0:
return colors
colors[num-1][index] = 'G' if colors[num-1][index] == 'B' else 'B'
num -= 1
changeColumn(num,colors,index)

def countGold(c,options,i):
if options == []:
s = 0
for l in c:
s += l.count("G")
print(s)
return
area = options[i][0]
times = int(options[i][1]) - 1
if area == "R":
c[times] = list(''.join(c[times]).replace("G","A").replace("B","G").replace("A","B"))
elif area == "C":
changeColumn(m,c,times)



options.remove(options[i])
countGold(c,options,i)

countGold(colors,stroke,0)

除了一些问题,一切都很好。我超过了4秒的时间限制。我知道制作colors需要很多时间。有没有办法在不生成2d数组的情况下做到这一点?

更新代码(无效)

import sys
M = int(input())
N = int(input())
K = int(input())
dup = []
numR = 0
numC = 0
for i in range(K):
choice = input().split()
if choice not in dup:
if choice[0] == "R":
numR += 1
elif choice[0] == "C":
numC += 1
dup.append(choice)

print((M * numR) + (N * numC) - (2*numR*numC))

让我把所有评论中的讨论都放到代码中:

import sys
M = int(input())
N = int(input())
K = int(input())
dup = set()
result = {'numR': 0, 'numC': 0}
def update(char, num):
if char == 'R':
result['numR'] += num
elif char == 'C':
result['numC'] += num
for i in range(K):
choice = input().split()
if choice in dup:
dup.remove(choice)
update(choice[0], -1)
else:
dup.add(choice)
update(choice[0], 1)
numR = result['numR']
numC = result['numC']
print((M * numR) + (N * numC) - (2*numR*numC))

Freakish发送的代码由于某种原因仍然无法工作。这是一个更新的代码,工作:

import sys
rw = sys.stdin.readline
M = int(rw())
N = int(rw())
choices = set()
K = int(rw())
for i in range(K):
g = input()
if g in choices:
choices.remove(g)
else:
choices.add(g)

numR = 0
numC = 0
s = 0
for choice in choices:
if choice[0] == "R":
numR += 1
elif choice[0] == "C":
numC += 1

for choice in choices:
if choice[0] == "R":
# numR += 1
s += N - numC
elif choice[0] == "C":
# numC += 1
s += M - numR

print(s)

最新更新