题目名称:豚鼠排名榜
时间限制: 1000ms 内存限制: 256M
题目描述
已知字符A.B,C。每个字符都有自己的权值q。 现不知道权值q,只知道A,B,C的三次比较结果。
输入描述
输入三个字符串表示三次比较的结果
输出描述
输出结果,如果不存在输出”Impossible”
示例
示例1
输入:
A < B
B > C
C > A
输出:
ACB
class Solution:
def __init__(self) -> None:
pass
def solution(self, exp1, exp2, exp3):
relationships = {'A': [], 'B': [], 'C': []}
comparisons = [exp1, exp2, exp3]
for comparison in comparisons:
char1, char2 = comparison[0], comparison[2]
if comparison[1] == '<':
relationships[char1].append(char2)
elif comparison[1] == '>':
relationships[char2].append(char1)
order = []
visited = set()
def dfs(char):
visited.add(char)
for next_char in relationships[char]:
if next_char not in visited:
dfs(next_char)
order.append(char)
for char in relationships.keys():
if char not in visited:
dfs(char)
if len(order) != 3:
return "Impossible"
return ''.join(order[-1::-1])
if __name__ == "__main__":
exp1 = input().strip()
exp2 = input().strip()
exp3 = input().strip()
sol = Solution()
result = sol.solution(exp1, exp2, exp3)
print(result)
通过率只有90%,不知道为啥?