from collections import deque, defaultdict
def toposort(g,rd,n):
path = []
queue = deque([])
cnt = 0
for node in g:
if rd[node] == 0:queue.append(node)
while queue:
cur = queue.popleft()
path.append(cur)
cnt += 1
for child in g[cur]:
rd[child] -= 1
if rd[child] == 0:queue.append(child)
flag = False
for i in rd:
if rd[i] > 0:
flag = True
break
return [path,flag]
gdeep = 0
def dfs(node,deep,topo,vis,g):
global gdeep
gdeep = max(gdeep,deep)
if vis[node] == 1:return deep
vis[node] = 1
for child in g[node]:
if vis[child] == 0 and child == topo[deep]:
dfs(child,deep + 1,topo,vis,g)
def solve():
n, m = map(int, input().split())
g = defaultdict(lambda: [])
rdfa = defaultdict(lambda: 0)
# 如果拓扑序的长度>=n,则直接返回前n个,(注意是拓扑链条)
# 如果无法确定关系,则优先输出有矛盾的
for i in range(m):
u, v = input().split('<')
if u == v:
return f'Inconsistency found after {i + 1} relations.'
g[u].append(v)
rdfa[v] += 1
rd = rdfa.copy()
topo,ishuan = toposort(g,rd,n)
# 求深度
dfs(topo[0],1,topo,defaultdict(lambda : 0),g)
# 链条深度到达则直接返回
if gdeep==n :
ans = ''.join([str(x) for x in topo])
return f'Sorted sequence determined after {i + 1} relations: {ans}.'
if ishuan:
return f'Inconsistency found after {i + 1} relations.'
return 'Sorted sequence cannot be determined.'
print(solve())
测试点2的数据为
4 6
C<D
C<B
B<A
C<D
D<A
A<A
本地输出
Inconsistency found after 6 relations.
跟评测机的结果一样 但是为什么我线上评测机提示错误信息是首字母开头为S??