题解:P5698 [CTSC1998] 算法复杂度

· · 题解

P5698

这是一篇 Python 3 题解。 不过你也可以进来看看思路。

主要思路:模拟

把遍历到的当前的最小循环计算并在原位置替换。

那么对于样例1中的第一个循环就是这么处理的:

loop n loop 3 loop n
op 20
end end end

变为

loop n loop 3
op 20n
end end

变为

loop n
op 60n
end

变为

op 60n^2

题中需要注意的

写代码

1. 读入

用两个变量分别储存 loop 和 end 的数量,一旦 end 的数量超过 loop 的数量就退出读入的循环。

l,lpt,edt=[],0,0 #用列表l储存读入,用lpt和edt来储存loop和end的数量
while True:
    s=input().split() #读入,存储于列表s
    lpt+=s.count('loop')
    edt+=s.count('end')
    l+=s #合并列表,列表l的末尾接上列表s
    if edt>lpt: #上面提及的退出条件
        break
l=l[1:-1] #删去开头的begin和最后一个end

2. 计算当前的最小循环并在原位置替换

用 while 循环和累加器 x 遍历列表 l,如果找到当前的最小循环就计算并在原位置替换,然后从头开始遍历。\ 涉及多项式加减以及单项式乘多项式,所以要写个函数将 n 或常数转列表。

def num_to_list(g): #输入只会是一个列表或者n或者一个常数
    if type(g)==list: #如果已经是列表就不用转
        return g
    if g=='n': #处理n
        return [0]*20+[1,0]
    else: #处理常数
        return [0]*21+[int(g)]

如果所有的循环都被计算完毕那就不会遍历到 loop ,这时列表 l 会超出索引范围抛出 IndexError,可以用 try...except...else 解决,其中 except 下的语句退出循环。

x=-1 #初始化累加器x
while True:
    x+=1
    try:
        l[x]
    except:
        break #退出循环
    else:
        if l[x]=='loop':
            for y in range(x+1,len(l)):
                if l[y]=='loop':
                    y=''
                    break #loop后面还有loop,退出当前循环,y为空,后面的if语句不会执行
                if l[y]=='end':
                    break #此时end的下标被储存到y
            if y:
                temp=[] #用列表temp存当前最小循环
                for _ in range(y-x+1): #y-x+1是列表temp的长度
                    te=l.pop(x)
                    if te!='end': #不存end
                        temp.append(te)
                for z in range(len(temp)): #处理continue和break
                    if temp[z]=='continue':
                        temp=temp[:z] #去掉continue及其后面语句
                        break
                    if temp[z]=='break':
                        temp=temp[2:z] #去掉loop x,break及其后面语句
                        break
                if temp==[]: #如果处理完后列表temp为空,就是说实际上当前最小循环不会对复杂度有贡献
                    l.insert(x,[0]*22) #替代为0
                    l.insert(x,'op') #统一格式
                    x=-1 #重置累加器x从头开始遍历
                    continue
                lo='1' #循环次数为lo
                if temp[0]=='loop': #将loop x的x存到lo
                    lo=temp[1]
                    temp=temp[2:]
                for _ in range(temp.count('op')): #去除列表temp中所有的op
                    temp.remove('op')
                temp=list(map(num_to_list,temp)) #将列表temp中的n和常数全部转成列表,方便后面计算
                tempp=[0]*22 #初始化计算后的列表temp
                if lo.isdigit(): #如果循环次数是常数此时会是一个字符串
                    lo=int(lo)
                    for m in range(22):
                        for n in temp:
                            tempp[m]+=n[m]*lo
                else: #循环次数是n
                    for m in range(22):
                        for n in temp:
                            tempp[m]+=n[m]
                    tempp=tempp[1:]+[0]
                l.insert(x,tempp) #把运算后结果替代当前最小循环
                l.insert(x,'op')
                x=-1 #重置累加器x

3. 处理结果

题中有说可能会有 continue 或 break 不在任何循环内,所以此时列表 l 里可能会有 continue 或 break,一定有 op 和至少一个列表(至少一个多项式),需要去除所有 continue 和 break 和 op。

for x in 'break','continue','op':
    for _ in range(l.count(x)):
        l.remove(x)

当然也可能有 op x 不在循环内还未被处理过,所以处理一遍。

l=list(map(num_to_list,l))

把列表 l 中所有的列表计算为一个列表 ltemp,然后替换列表 l。

ltemp=[0]*22
for x in range(22):
    for y in l:
        ltemp[x]+=y[x]
l=ltemp

4. 输出

如果做过 P1067 [NOIP 2009 普及组] 多项式输出 或 P2281 [HNOI2003] 多项式的加法和乘法 可能会对你有所帮助。\ 先判断列表 l 是否为空,是空的就输出 0,不是就继续。

if all([x==0 for x in l]):
    print(0)
    exit()

此时列表 l 已经是降幂。\ 输出时需要注意

用 l_n 代表列表 l 的第 n 个元素 (0\le n\le21)。

flag=False
for x in range(22):
    if l[x]==0: #为0不输出
        continue
    if x==21: #最后一项直接输出
        print(f'+{l[-1]}')
        exit()
    if flag and l[x]!=0: #本项非空就输出加号(+)
        print('+',end='')
    if l[x]>1: #系数大于1就不省略
        print(l[x],end='')
    print('n',end='')
    if x!=20: #次数大于1就不省略
        print(f'^{21-x}',end='')
    if (not flag) and l[x]!=0: #判断是否为是列表l中第一个非0的元素
        flag=True

:::success[AC Code(Python 3)]

l,lpt,edt=[],0,0
while True:
    s=input().split()
    lpt+=s.count('loop')
    edt+=s.count('end')
    l+=s
    if edt>lpt:
        break
l=l[1:-1]
def num_to_list(g):
    if type(g)==list:
        return g
    if g=='n':
        return [0]*20+[1,0]
    else:
        return [0]*21+[int(g)]
x=-1
while True:
    x+=1
    try:
        l[x]
    except:
        break
    else:
        if l[x]=='loop':
            for y in range(x+1,len(l)):
                if l[y]=='loop':
                    y=''
                    break
                if l[y]=='end':
                    break
            if y:
                temp=[]
                for _ in range(y-x+1):
                    te=l.pop(x)
                    if te!='end':
                        temp.append(te)
                for z in range(len(temp)):
                    if temp[z]=='continue':
                        temp=temp[:z]
                        break
                    if temp[z]=='break':
                        temp=temp[2:z]
                        break
                if temp==[]:
                    l.insert(x,[0]*22)
                    l.insert(x,'op')
                    x=-1
                    continue
                lo='1'
                if temp[0]=='loop':
                    lo=temp[1]
                    temp=temp[2:]
                for _ in range(temp.count('op')):
                    temp.remove('op')
                temp=list(map(num_to_list,temp))
                tempp=[0]*22
                if lo.isdigit():
                    lo=int(lo)
                    for m in range(22):
                        for n in temp:
                            tempp[m]+=n[m]*lo
                else:
                    for m in range(22):
                        for n in temp:
                            tempp[m]+=n[m]
                    tempp=tempp[1:]+[0]
                l.insert(x,tempp)
                l.insert(x,'op')
                x=-1
for x in 'break','continue','op':
    for _ in range(l.count(x)):
        l.remove(x)
l=list(map(num_to_list,l))
ltemp=[0]*22
for x in range(22):
    for y in l:
        ltemp[x]+=y[x]
l=ltemp
if all([x==0 for x in l]):
    print(0)
    exit()
flag=False
for x in range(22):
    if l[x]==0:
        continue
    if x==21:
        print(f'+{l[-1]}')
        exit()
    if flag and l[x]!=0:
        print('+',end='')
    if l[x]>1:
        print(l[x],end='')
    print('n',end='')
    if x!=20:
        print(f'^{21-x}',end='')
    if (not flag) and l[x]!=0:
        flag=True

::: :::info[Update] 2026.6.14:修改格式使整体更美观,并对内容(4 .输出)做出一定改进,且对更新的 Callouts 做出适应。 :::