2016-02-27 69 views
-1

我學習的快速合併算法,但不能準確地理解這段代碼:這段代碼的解釋?

#include <stdio.h> 
#define N 10000 
main() 
{ 
    int i,p,t,id[N]; 
    for (i = 0; i < N ; i++) id[i]= i; 
    while (scanf ("%d %d\n" , &p, &q) == 2) 
    { 
    for(i = p; i != id[i]; i = id[i]) ; 
    for (j = q; j != id[j]; j = id[j]) ; 
    if (i == j) continue; 
    id [i] = j ; 
    } 
} 

我的主要問題是for循環。如果符合conditioninit,增量語句會做什麼?

注意:這不是我的代碼的教科書!

+0

你在這裏發帖之前做測試輸入預演? – goelakash

+0

你用'#define N 5'之類的東西試了一下,並給它提供了一些值嗎? –

+0

'for'循環大致等同於'{initialization; while(condition){body in loop;增量}}'嘗試像這樣更改代碼,然後在調試器中逐行執行代碼。它應該可以幫助你理解發生了什麼。 –

回答

1

這是union-find數據結構的內聯實現。聯合查找數據結構將不相交的集合表示爲樹。它將每個節點的父節點存儲在id數組中。最初,每個節點都是它自己的父節點(形成一個單獨的樹)。這是,什麼下面一行所做的:

for (i = 0; i < N ; i++) id[i]= i; 

隨着你遍歷樹行

for(i = p; i != id[i]; i = id[i]) ; 

,其中p所在,達到它的根。部分i = id[i]將當前節點更改爲當前節點的父節點。

對於q也是這樣做的。最後,如果兩棵樹不是同一棵樹,它們就會合並。

id [i] = j ; 
+0

這比現在接受的答案要好得多。 –

-1

首先使用返回類型爲int main函數的按照標準

爲(I = 0;我< N; i ++在)ID [I] = I; 這個循環寫入到陣列id[i]所有值從0到N

while (scanf ("%d %d\n" , &p, &q) == 2) 
    { 
    for(i = p; i != id[i]; i = id[i]) ; 

//在這個循環中它以來自用戶的輸入並檢查相同的,如果它是在該陣列ID具有相同索引如果條件爲真,您將使用索引中的值分配給我。

//如果條件沒有滿足,將進入下一個循環

 for (j = q; j != id[j]; j = id[j]) ; 

//與上面不同的輸入迴路。 if(i == j)continue; id [i] = j; }

-1

這裏是一個解釋,我的理解代碼:

#include <stdio.h> 

#define N (10000) 

int main(void) 
{ 
    int i; 
    int p; 
    int t; 
    int id[N]; 

    // initialize array id[] 
    for (i = 0; i < N ; i++) 
    { 
     id[i]= i; 
    } 

    /* 
    * IMO: 
    * bad idea to be asking for two integers without prompting the user 
    * bad idea to use the two values without checking that they are in the range 0...(N-1) 
    * this code performs nothing useful 
    * the array id[] becomes more 'modified' the more numbers are entered 
    * */ 

    // read two integers, if successful then 
    while (scanf ("%d %d\n" , &p, &q) == 2) 
    { 
     // looping, searching array id[] to see if properly initialized/updated 
     for(i = p; i != id[i]; i = id[i]) ; 

     // looping, searching array id[] to see if properly initialized/updated 
     for (j = q; j != id[j]; j = id[j]) ; 

     // when same value extracted from array id[] for both inputs then 
     // return to top of loop 
     if (i == j) continue; 

     // when not the same value, update array id[] with other value 
     id [i] = j ; 
    } 
}