[英]Last node in graph traversing with Q queries
Given a directed graph with N nodes(1<=N<=100000) Each node will have only one outgoing edges but there can be more than one incoming edges.给定一个有 N 个节点的有向图(1<=N<=100000),每个节点只有一个出边,但可以有多个入边。 There are Q(1<=Q<=10^5) queries where each query is of 2 types.
有 Q(1<=Q<=10^5) 个查询,其中每个查询有 2 种类型。
I know we can solve this ques in O(N) complexity per query(with overall complexity of QN ), but since the no of queries are high (10^5) this doesn't seems to be the efficient solution?我知道我们可以在每个查询的 O(N) 复杂度中解决这个问题(总体复杂度为 QN ),但是由于查询的数量很高(10^5),这似乎不是有效的解决方案?
Any idea how to solve this with better time complexity?知道如何以更好的时间复杂度解决这个问题吗? Thanks
谢谢
If you don't need to answer queries online, the easy way is to implement union-find with path compression and process the input backward.如果您不需要在线回答查询,最简单的方法是使用路径压缩实现 union-find 并向后处理输入。 Initialize by linking each arc that is never deleted (with the special case below).
通过链接每个永远不会被删除的弧来初始化(使用下面的特殊情况)。 Scanning backward, for a query of the second type, add the arc, unless it would create a cycle, in which case link the tail to a special vertex with id -1.
向后扫描,对于第二种类型的查询,添加弧,除非它会创建一个循环,在这种情况下,将尾部链接到 id 为 -1 的特殊顶点。 To answer the first kind of query, find the root with path compression.
要回答第一种查询,请使用路径压缩找到根。 The running time will be O((Q + N) log N).
运行时间将为 O((Q + N) log N)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.