[英]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) )
該圖也可以有循環,如上圖所示。 所以我想轉換為樹是不可能的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.