1. 程式人生 > >CCF Python題解(100分)201809-3 元素選擇器

CCF Python題解(100分)201809-3 元素選擇器

CCF Python題解(100分)201809-3 元素選擇器

n, m = map(int, input().split())
textlist = []
for i in range(n):
    text = input()
    level = text.count('.') // 2
    tag = ""
    id = ""
    if len(text.split()) == 1:  # 標籤
        tag = text
    else:
        tag, id = text.split()
    tag = tag.strip('.')
    pline =
-1 for j in range(i - 1, -1, -1): if textlist[j]['level'] == level - 1: pline = j + 1 break textlist.append({'tag': tag, 'id': id, 'level': level, 'pline': pline, 'line': i + 1}) def f(pline, i, count): if pline - 1 < 0: return False text =
textlist[pline - 1] pline = text['pline'] if select[i].upper() == text['tag'].upper() or select[i] == text['id']: # 匹配到 count += 1 if i == 0 and count == len(select): return True else: if f(pline, i - 1, count): return True else
: if f(pline, i, count): return True else: return False for i in range(m): select = input() if len(select.split()) == 1: # 標籤或id count = 0 str1 = "" for text in textlist: if text['id'] == select or text['tag'].upper() == select.upper(): count += 1 str1 += " " + str(text['line']) print(count, end="") print(str1) else: # 後代 select = select.split() list = [] j = len(select) - 1 for text in textlist[::-1]: if text['tag'].upper() == select[j].upper() or text['id'] == select[j]: line = text['line'] pline = text['pline'] if f(pline, j - 1, 1): list.append(line) print(len(list), ' '.join(map(str, list[::-1])))