繁体   English   中英

在压缩有向图中检测循环?

[英]Detecting a cycle in a compressed directed graph?

我正在为考试学习,无法解决此问题:

我们给了一个n == 30万个节点的图,但它是压缩形式。 这种形式由m <= 30万行组成,每行由三个数字给出:a_i,b_i,c_i,这意味着从间隔[b_i,c_i]到节点a_i到所有节点都有定向边。 问题是要确定给定图中是否存在一个循环,或者不存在。

例如输入:(先编号n,m,然后再编号m行描述图形)

4 5

1 2 3

1 4 4

2 3 4

3 4 4

4 1 1

答案为是(例如,循环:1-> 2-> 3-> 4-> 1)

对于此输入:

4 4

1 2 3

1 4 4

2 3 4

3 4 4

答案是不。

因此,主要问题是该图可能非常庞大,我无法负担创建它并运行DFS的费用。 它必须更快地完成。 我的第一个想法是使用拓扑排序算法。 如果有效,则给定图中没有周期,否则存在周期。 但是很难更新节点的度数(以便在此算法的每个步骤中选择deg_in = 0的节点)。 我当时在想,也许使用间隔树会对此有所帮助-当我删除节点v时,我可以看到他的邻接列表(此列表中的元素将被赋予间隔),并且对于所有间隔,这些点的deg_in都会递减。 因此,我可以检查对数时间内的某个节点度,但是仍然无法快速更新deg_in = 0的节点列表。 我不知道,也许我正在尝试无法解决的解决方案?

有人可以帮忙吗?

我将尝试为该算法制作一个元代码。 这将是图旅行算法的特例。 专业是关于生产线的包装存储。

// Outer loop to check all nodes
CheckedNodes = (empty)
for n1 in 1 .. n {
    if (not(CheckedNodes contains n1)) {
        add n1 to CheckedNodes
        VisitedNodes = (empty) // initialization
        VisitableNodes = { n1 } // start the walk from here
        // Inner loop to walk through VisitableNodes
        While (VisitableNodes is not empty) {
            n2 := select one from VisitableNodes
            remove n2 from VisitableNodes
            add n2 to CheckedNodes // this will stop processing again
            for all lines starting from n2 { // we add all points for all lines
                for n3 in line.start .. line.end { 
                    if (VisitedNodes contains n3) { 
                        // we found an already visited node
                        return "Circle found in Graph!" 
                    } else {
                        // otherwise we should visit that later
                        add n3 to VisitableNodes
                    }
                }
             }
        }
    }
}
// we have not found a circle
return "No circle found in Graph!"

问题是实施。 在这里,在我使用Sets的CheckedNodesVisitedNodes算法中,它们-具有整数索引-可以通过布尔数组(或类似方法)轻松实现。 VisitableNodes是一个列表,它应该由类似列表的结构实现。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM