1. 程式人生 > 其它 >資料結構11 DFS&Insert Sort

資料結構11 DFS&Insert Sort

技術標籤:資料結構

DFS

按照深度優先遍歷一張圖

無向圖:

input:源點根V

1.visit[V]=True

2.對於所有與V鄰接的點,if ( !visited[ W ] ) DFS( W );

複雜度為O(E+V)

articulation point:刪除後聯通分量會增加

biconnected graph :G是聯通的,且沒有銜接點

biconnected component:最大的雙連通子圖

尋找銜接點:

1.使用DFS生成樹,但是不在樹中的邊需要用虛線加入到樹中(back edge)

2.根節點是連線點:至少有兩個孩子

3.其他結點是連線點:從該結點往下走不能回到祖先。(孩子中沒有後繼邊)

Num(u):該結點的編號,對應生成樹時的順序。Num(root)=0

Low(u)=min{Num(u),Low(any u's child),Low(u),w和v用後繼邊相連。}

演算法2:

1.使用DFS生成樹

2.計算num和Low

3.根是連線點:至少有兩個孩子

4.非根節點是連線點:有一個孩子:Low(child)>Num(u)

插入排序

void InsertionSort ( ElementType A[ ], int N ) 
{ 
      int  j, P; 
      ElementType  Tmp; 

      for ( P = 1; P < N; P++ ) { 
	    Tmp = A[ P ];  /* the next coming card */
	for ( j = P; j > 0 && A[ j - 1 ] > Tmp; j-- ) 
	      A[ j ] = A[ j - 1 ]; 
	      /* shift sorted cards to provide a position 
                       for the new coming card */
	    A[ j ] = Tmp;  /* place the new card at the proper position */
      }  /* end for-P-loop */
}

總是將有序陣列的後一個元素插入到有序陣列中。

有序陣列從一個元素開始。

最壞情況:逆序O(N^2)

最好情況:順序O(N)

平均情況:O(N^2)

inversion:兩個元素的位置是逆序的。

有幾個逆序對就需要交換幾次,若有I個逆序對,時間複雜度為O(N+I)

題目

1.For a graph, if each vertex has an even degree or only two vertexes have odd degree, we can find a cycle that visits every edge exactly once

尤拉環的條件是所有點的度數為偶數,F

2.After the first run of Insertion Sort, it is possible that no element is placed in its final position.

如果是逆序,只有兩個元素,則可以。T

3.Apply DFS to a directed acyclic graph, and output the vertex before the end of each recursion. The output sequence will be:

A.unsorted

B.topologically sorted

C.reversely topologically sorted

D.None of the above

遞迴的順序是遍歷1->遍歷2->遍歷3->.....->遍歷n->返回n->返回n-1...->返回3->返回2->返回1

返回的時候列印,因此是從最後一個結點開始列印到源點。是逆拓撲序。

4.Graph G is an undirected completed graph of 20 nodes. Is there an Euler circuit in G? If not, in order to have an Euler circuit, what is the minimum number of edges which should be removed from G?

A.Yes, Graph G has an Euler circuit

B.No, Graph G has no Euler circuit. 10 edges should be removed.

C.No, Graph G has no Euler circuit. 20 edges should be removed.

D.No, Graph G has no Euler circuit. 40 edges should be removed.

20個點的完全圖,每個點的度數為19,尤拉圖每個點的必須是一個偶數,因此使得每一個點的度數是18,一條邊對應兩度,減少的邊為:20*1/2=10

5.Given the adjacency matrix of a graph as shown by the figure. Then starting from V5, an impossible DFS sequence is:

72.jpg

A.V5, V6, V3, V1, V2, V4

B.V5, V1, V2, V4, V3, V6

C.V5, V1, V3, V6, V4, V2

D.V5, V3, V1, V2, V4, V6

鄰接矩陣是對稱的,所以是一個無向圖。一對一對檢查是不是相鄰。發現6和4是不相鄰的 C

6.Use simple insertion sort to sort 10 numbers from non-decreasing to non-increasing, the possible numbers of comparisons and movements are:

A.100, 100

B.100, 54

C.54, 63

D.45, 44

看似好像很複雜:10個元素逆序的話:有C(10,2)=45的逆序對,因此交換的數目不會大於45 D

7.Given a sorted file of 1000 records. To insert a new record by insertion sort with binary search, the maximum number of comparisons is:

A.1000

B.999

C.500

D.10

注意不是線性插入,是二叉插入,因此是log2 100,應該是D