基础算法系列之 The Blocks Problem

传送门:https://www.luogu.org/problemnew/show/UVA101

题意翻译

初始时从左到右有n个木块,编号为0~n-1,要求实现下列四种操作:

move a onto b: 把a和b上方的木块全部放回初始的位置,然后把a放到b上面
move a over b: 把a上方的木块全部放回初始的位置,然后把a放在b所在木块堆的最上方
pile a onto b: 把b上方的木块部放回初始的位置,然后把a和a上面所有的木块整体放到b上面
pile a over b: 把a和a上面所有的木块整体放在b所在木块堆的最上方
一组数据的结束标志为"quit",如果有非法指令(a和b在同一堆),应当忽略。

输入输出样例

输入样例#1:

10
move 9 onto 1
move 8 over 1
move 7 over 1
move 6 over 1
pile 8 over 6
pile 8 over 5
move 2 over 1
move 4 over 9
quit

输出样例#1:

0: 0
1: 1 9 2 4
2:
3: 3
4:
5: 5 8 7 6
6:
7:
8:
9:

python实现

# coding: utf-8
"""
create by ljf on 2019/3/8 15:02
"""
n = int(input("the number of blocks is "))
default = {
    
    str(id):[id] for id in range(n)}
print(default)
while True:
    command = input("please input your command: ").split()
    if command == ["quit"]:
        break
    a,b = 1,1
    # case 1 归位
    if command[0] == "move":
        # 循环归位
        for i in default[command[1]][1:]:
            default[i] = i
    elif command[2] == "onto":
        # 循环归位
        for k in default[command[3]][1:]:
            default[k] = k
    # case 2 移动
    # 将a和a上面所有的木块放到b的最上面
    stack1,stack2 = [],[]
    m,s1,s2= 0,0,0
    for i in range(n):
        # 过滤掉没有blocks的堆
        if len(default[str(i)]) == 0:
            continue
        else:
            for j in range(len(default[str(i)])):
                # 找到数字1所在堆号
                if int(command[1]) == default[str(i)][j]:
                    # 将a所在堆分为两块,一块移到b所在堆上面,一块留在原堆上,获取a所在堆号
                    stack1,stack2 = default[str(i)][:j],default[str(i)][j:]
                    s1 = i
                # 找到数字2所在堆号
                if int(command[3]) == default[str(i)][j]:
                    s2 = i

                # 将blocks放到对应的堆号上
                if s1!=0 and s2!=0:
                    default[str(s1)] = stack1
                    default[str(s2)] += stack2
                    m = 1
                if m ==1:
                    break
        if m ==1:
            break

    # print(default)
for item in default.items():
    print(item)

注:洛谷平台上面的算法基本是C++实现的。有不足之处还请多多指教!

猜你喜欢

转载自blog.csdn.net/weixin_42662358/article/details/91360032