Question

i have an assignment in algorithm and have to write a pseudo code for the problem which is like Given set of n sticks resting on top of each other in some configuration. A class Stick that has a method on such that for Sticks a and b, a.on(b) returns true exactly when stick a is resting on b. A stick only can be picked if its there is no stick on it.. i have wrote the following pseudo-code for it can anyone tellme if i am doing it write....

Begin 
 For each stick s(v) 
  Construct a vertex v for Graph G; 
 End For 

 if a.on(b) 
 Return True; 
 Else 
 Return False; 
 End If 

 TopologicalSort(G); 
 If cycle is found by TopologicalSort 
 Return No; 
 Else 
 Return the order of each stick produced by TopologicalSort; 
 End If 
End

Running time of this algorithm will be O(n) time

Was it helpful?

Solution

First form an array below[] where below[i] = stick no. that is below stick No. i ( i = 0 to N-1 )

for ( int i = 0; i < N; i++ ) {
  int stickBelow = -1;
  for ( int j = 0; j < N; j++ )
    if ( i.on( j ) {
      stickBelow = j;
      break;
    }
  below[i] = stickBelow;
}

Now iterate over this array, and keep choosing the stick whose below[i] is the present stick on top.

int topStick = -1;
for ( int i = 0; i < N; i++ ) {
  for ( int j = 0; j < N; j++ ) {
    if ( below[j] == topStick ) {
      Choose the stick j;
      topStick = j;
      break;
    }
  }
}

The above algorithm has order of complexity O(N^2).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top