12.19 Python教程——NOIP的算答题-救济金发放顺序

大家好,我是酷叮猫少儿编程的郭老师,今天我为大家带了一道NOIP的算答题。

请看下题:

n个人站成一圈(n<20),逆时针编号为1~n.有两个官员,A从0逆时针数,B从n开始顺时针数.在每一轮中,官员A数k个就停下来,官员B数m个就停下来(注意有可能两个官员在同一个人上)。接下来被官员选中的人(1或2人)离开队伍.

输入n,k,m输出每轮里被选中的人的编号(如果有两个人,先输出被A选中的)。

例如,n=10,k=4,m=3

输出为4 8,9 5,3 1,2 6,10,7.注意:每轮输出的数应当恰好占3列.

[样例运行结果如图]


Python教程——NOIP的算答题-救济金发放顺序


[代码]

def go(nlist, p, d, t):

# p from 0 to leng-1

# d = 1 or -1

np = p

leng = len(nlist)

idlist =[]

for _ in range(t):

while True:

if nlist[np]>0:

idlist.append(np)

break

else:

np = (np + d + leng) % leng # np 递增或递减, 并循环

np = (np + d + leng) % leng

return idlist[-1]

def main():

ans=[]

nkm = input("Please input n k m:")

nkm = [x.strip() for x in nkm.split()]

while True:

try:

n,k,m = [int(x) for x in nkm]

break

except:

print("Try again: input n k m:")

nlist = list(range(1,n+1))

left = n

pa = 0 #A官员的逆时针起点

pb = n-1 #B官员的顺时针起点

while left:

pa = go(nlist, pa, 1, k)

pb = go(nlist, pb, -1, m)

if pa==pb:

print("{}".format(nlist[pa]), end="")

nlist[pa]=0

left-=1

else:

print("{} {}".format(nlist[pa], nlist[pb]), end="")

nlist[pa], nlist[pb] = 0,0

left -= 2

if left>0:

print(",", end="")

print()

# print(nlist)

if __name__=="__main__":

main()

好的,就到这里吧。如果大家有什么不太明白的地方,留言哟. 下次见。Bye!


分享到:


相關文章: