题解:P10486 [入门赛 #25] sql

· · 题解

处理输入时对于每张二维表记录两个信息:从表头名到编号的映射 header_map 和表的内容 content ,存储在一个可以通过表名查询到的映射 table 中。
处理语句时,先通过表名查询到对应的 header_map 和 content。通过 header_map 将 columns 中的每个表头和要查询的表头转化为编号,再在 content 中逐行查找符合条件的行,输出对应的列。

table = {}
for _ in range(int(input())):
    name = input()
    H, W = map(int, input().split())
    headers = input().split()
    content = [input().split() for _ in range(H - 1)]

    # 表头名到编号的映射
    header_map = {headers[i]: i for i in range(W)} 
    table[name] = (header_map, content)

for _ in range(int(input())):
    _, columns, _, name, _, headerx = input().split() # headerx 即为输入中的 [header]=x 部分
    header_map, content = table[name]
    header, X = headerx.split('=') # 用 = 分开它们

    # 转化为编号
    header_idx = header_map[header]
    column_indices = [header_map[h] for h in columns.split(',')]

    # 逐行查询
    for row in content:
        if row[header_idx] == X:
            print(' '.join(row[i] for i in column_indices))