簡體   English   中英

有向圖中兩個給定節點的最近相遇節點

[英]nearest meeting node of two given nodes in a Directed Graph

我得到了一個有向圖,並在其中給出了兩個節點,我需要找到可以從它們兩個都到達的最近節點。 唯一的問題是我可以用兩個 dfs 來完成,但我被告知要在 O(logn) 中完成。 額外的限制是每個單元最多可以有一個輸出邊。 輸入作為大小為 N 的數組給出,其中數組中的每個條目表示該節點所指向的節點的索引。 所以這是我嘗試過的代碼(不完全是 dfs 但仍然):

int leastCommonDescendent(int nodes[], int N, int node1, int node2)
{
  int *visited = new int [N];
  int cnt1 = 0; //used for counting length of path from node1 to node2
  int cnt2 = 0; //used for counting length of path from node2 to node1
  int mark = node1; //storing as a marker needed later for detecting end of search

  if(node1 == node2) return node2;
  for(int i = 0; i < N; i++){
    visited[i] = 0;
  }

  while((nodes[node1] != node1) && (nodes[node1] != -1) && (visited[node1] == 0) && (node1 != node2)){
    visited[node1]++;
    node1 = nodes[node1];
    cnt1++;
  }

  visited[node1]++; //so that first node in cycle has count 2
                    //if find a node in 2nd iteration that has count 2
                    //such that when node1 == node2 it means we are in the same subgraph
                    //elsif node1 != node2 we are in different sub graphs

  while((nodes[node2] != node2) && (nodes[node2] != -1) && (visited[node2] != 2) && (node1 != node2)){
    visited[node2]++;
    node2 = nodes[node2];
    cnt2++;
  }
  //In below case the nodes are in different disjoint subgraphs
  //and both subgraphs have loops so node1 can never be equal to node2
  //cout << visited[node1] << visited[node2] << endl;
  if(node1 != node2) return -1;
    //In below case both nodes are in different disjoint subgraphs
    //but there is no loop in 1st one(containing node1)
    //and 2nd one has a loop
  if ((nodes[node1] == -1) && (visited[node2] == 1)) return -1;
    //In below case both nodes are in different disjoint subgraphs
    //but 1st one has a loop and second one doesn't
  if(nodes[node2] == -1) return -1;
    //In below case both nodes are in same subgraph so we
    //need to check the length of two alternate paths
  if(cnt1 > cnt2)
    return node2;
  else
    return mark;
}  

假設我有一個圖的組件(本質上是一個子圖),如下所示:
在此處輸入圖片說明

在這種情況下,如果我想找到7和9的最近的節點,我得到了答案9,而應該是8,雖然我明白那是因為我的條件小區1!=在這兩個循環的小區2,但我會為整個周期以防我刪除邀請更多時間的內容。 我也覺得這個解決方案雜亂無章。 我們可以有一個更簡單的解決方案嗎? (可能基於O(logn)

該圖也可以有循環,如上圖所示。 所以我想轉換為樹是不可能的。

通過簡單地反轉圖形的鏈接,可以輕松地將其簡化為(或來自)樹中(或確切地說是森林中)中的最低共同祖先

通常,它可以在O(h) ,通過逐步“向上”樹(在原始圖中向前步進),並將找到的節點存儲在集合中,直到集合交集不為空。

如果允許預處理,可以預先處理它的線性時間,以獲得更好resilts。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM