Você está na página 1de 22

Question Paper Data Structures and Algorithm Analysis (MC211) : October 2005

Section A : Basic Concepts (30 Marks)


This section consists of questions with serial number 1 - 30. Answer all questions. Each question carries one mark. Maximum time for answering Section A is 30 Minutes.

1.

The suitable data structure to represent the data of rainfall of week days in ten cities of three states is __________ (a) Stack (d) Multi way tree (b) Queue (e) Connected graph. (c) Array

< Answer >

2.

The data structure which allows the insertion at both the ends, but allows the deletion at only one end is ________ (a) (b) (c) (d) (e) Output restricted Deque Input restricted Deque Circular queue Linear queue Priority queue.

< Answer >

3.

Searching the linked list requires linked list be created in _________ (a) Ascending order (b) Descending order (c) With underflow condition (d) Any order condition. (e) Without underflow

< Answer >

4.

The time complexity of binary search in best, worst cases for an array of size N is (a) N, N2 (b) N, N (c) Log N, N2 (d) 1, N log N (e) 1, log N. How many minimum number of spanning trees, one can have from a given connected graph with N nodes is having different weights for the edges. (a) N-1 (b) One (b) 2 exactly (c) 1/(N+1) 2NCN (c) More than two (d) 2NCN (d) 0 (e) N. How many children do an external node of a binary tree of order N contains. (a) N at least (e) N at most. In-order traversal of binary search tree implies visiting the nodes in __________ (a) (b) (c) (d) (e) Post-order The order of increasing magnitude of their key Pre-order The order of decreasing magnitude of their key N Arbitrary order.

< Answer >

5.

< Answer >

6.

< Answer >

7.

< Answer >

8.

For a binary tree the In-order traversal was found to be as HIGCEFD. Once the post-order traversal was conducted the output is IHGFEDC. What is the per-order for the given tree? (a) CGDHEIF (d) CDEFGHI (b) GHICDEF (c) CGHIDEF (e) Data insufficient and hence cant be answered.

< Answer >

9.

Breadth first search uses __________ as an auxiliary structure to hold nodes for future processing. (a) Stack (a) (b) (c) (d) (e) (b) Linked list (c) Graph (d) B-Tree (e) Queue.

< Answer >

10. Folding is a method of generating ________ A hash function Index function for a triangular matrix Header node for a circular linked list Linear probing Chaining. 1

< Answer >

11. This algorithm scans the list by swapping the entries whenever pair of adjacent keys are out of desired order. (a) Insertion sort (a) More than one (d) Exactly two (b) Quick sort (c) Shell sort (d) Bubble sort (e) Radix sort. 12. At a given node of a simple graph, the number of loops are _________ (b) Not more than one (c) Zero (e) Equal to the number of nodes of the graph.

< Answer >

< Answer >

13. In the linked list implementation of the stack, where does the push member function place the new entry on the linked list? (a) (b) (c) (d) (e) At the head At the tail After all other entries those are greater than the new entry After all other entries those are smaller than the new entry At null node.

< Answer >

14. I have implemented the queue with a circular array, keeping track of first, last, and count (the number of items in the array). Suppose first is zero, and last is SIZE-1. What can you tell me about count? (a) (b) (c) (d) (e) count must be zero. count must be SIZE count must be SIZE-2 count must be SIZE+1 count could be zero or SIZE, but no other values could occur.

< Answer >

15. Convert the following postfix expression to a fully-parenthesized infix expression:

< Answer >

A B C - D E + * F * +
(a) (b) (c) (d) (e) (A + ((B - C) * (D + E) * F)) (A + (((B - C) * (D + E)) * F)) A + (((B - C) * (D + E)) * F) (A + ((B - C) * (D + E)) * F) A + ((B - C) * (D + E)) * F.
< Answer >

16. The linked list would be able to make use of a ------------- whose value is the address of the location which stores the node. (a) integer (a) (b) (c) (d) (e) (b) float (c) char (d) void (e) pointer. 17. What kind of list is best to answer questions such as "What is the item at position n?" Lists implemented with an array Doubly-linked lists Singly-linked lists Doubly-linked or singly-linked lists are equally best Circular linked list implemented with priorities.

< Answer >

18. Consider the following pseudo code: declare a stack of characters while (there are more characters in the word to read ) { read a character push the character on the stack } while ( the stack is not empty) { pop a character off the stack write the character to the screen } What is written to the screen for the input "carpets"? (a) serc (b) steprac (c) carpets (d) ccaarrppeettss (e) stepr. 19. What is the value of the postfix expression 6 3 2 4 + - * (a) Something between 5 and 15 (b) Something between -5 and -15 (c) Something between 5 and -5 2

< Answer >

< Answer >

(d) Something between -15 and -100 (e) Something between 15 and 100. 20. Suppose we have a circular array implementation of the queue type, with ten items in the queue stored at data[2] through data[11]. The current SIZE is 22. Where does the insert method place the new entry in the array? (a) data[1] (b) data[22] (c) data[12] (d) data[11]
+

< Answer >

(e) data[21].
< Answer >

21. The mathematical definition for Omega can be defined as, provided f,g:NR and c is a positive constant and n > n0, (a) (b) (c) (d) (e) f(n) c. g(n) n f(n) c. g(n) n f(n) c + g(n) n f(n) c + g(n) n f(n) g(n) n.

22. The notation is __________ I. Symmetric. II. Reflexive. III. Transitive. (a) (b) (c) (d) (e) Only (I) above Only (II) above Only (III) above Both (I) and (II) above All (I), (II) and (III) above.

< Answer >

23. From the following pick the one which does not belongs to the same paradigm to which others belongs to. (a) (b) (c) (d) (e) Minimum & Maximum problem Knapsack problem Selection problem Merge sort Quick sort.

< Answer >

24. The OBST algorithm in worst case takes _______ time if all c(i, j )s and r(i, j)s are calculated. (a) (log n) I. II. (b) (n4) (c) (n3) (d) (n log n) (e) (n2). 25. Read the following statements carefully, and choose the correct answer For the Backtracking algorithms stack data structure is used. For the Branch-and-bound algorithms queue data structure is used.

< Answer >

< Answer >

(a) (I) is FALSE but (II) is TRUE (b) (I) and (II) both are FALSE (c) (I) is TRUE but (II) is FALSE (d) (I) and (II) both are TRUE (e) (II) is TRUE and (I) cant be defined. 26. The weighted array used in TVS problems for the following binary tree is __________

< Answer >

(a) (b) (c) (d)

[1,2,3,0,0,4,0,5,6] [1,2,3,0,0,4,0,5,0,0,0,0,6] [1,2,3,4,5,6] [1,2,3,0,0,4,5,6] 3

(e)

[1,3,5,2,4,6].
< Answer >

27. Let f, t: N R+, then t (n) (f (n)), iff f(n) O (t (n)) is known as __________ (a) Limit rule (d) Rule of consequences (b) Rule of inference (c) Duality rule (e) Rule of symmetricity.

28. Let f, t: NR 0, and t (n) O (f (n)) iff t(n) c.f (n) where c is positive real constant and n no, then no is ___________ (a) Upper bound (b) Lower bound (d) Threshold value (e) Maximum value. (c) Duality value

< Answer >

29. For the 15-puzzle problem if the initial arrangement is as follows, then the value of x used to find the reachability is ________ 1 9 2 10 (a) 0 (a) O(1) (b) 1 (b) O(log n) 3 11 4 12 (c) 8 (c) O(n2) 5 14 8 15 7 6 13 (d) 14 (d) O(n log n)

< Answer >

(e) 13.
< Answer >

30. The time taken by nondeterministic sorting algorithm is ______ (e) O(n).

END OF SECTION A

Section B : Problems (50 Marks)


1. a. b. This section consists of questions with serial number 1 5. Answer all questions. Marks are indicated against each question. Detailed workings should form part of your answer. Do not spend more than 110 - 120 minutes on Section B.

Define Algorithm. Also write about the characteristics and constraints on Algorithms. For the following statements, prove whether they are correct or wrong using appropriate rules. i. 3n + 2 = O(n2) ii. n3 + 105n2 = (n3) iii. 33n3 + 4n2 (n2) iv. n2 / log n (n2) v. 100n2 + 102 = O(n) (5 + 1 + 1 + 1 + 1+ 1 = 10 marks) < Answer > What is a Hamiltonian Graph? Write an algorithm for finding the Hamiltonian Cycles of the given graph. Write an algorithm to search an element following the divide and conquer rule. Also write about it time complexity. (5 + 5 = 10 marks) < Answer > Write an algorithm to solve the Knapsack problem following the dynamic programming. Also write about its time complexity. Define Sum of Subsets Problem, also write an algorithm to find the solution for the problem. (5 + 5 = 10 marks) < Answer > Explain about the general analogy of the greedy algorithms. Write a simple C program to evaluate a given post fix expression. (4 + 6 = 10 marks) < Answer > Write a C function to create a Binary Tree. What is meant by Minimum Cost Spanning trees? Write about the greedy approach to find the Minimum Cost Spanning trees. (5 + 5 = 10 marks) < Answer > END OF SECTION B

2.

a. b.

3.

a. b.

4.

a. b. a. b.

5.

Section C : Applied Theory (20 Marks)


This section consists of questions with serial number 6 - 7. Answer all questions. Marks are indicated against each question. Do not spend more than 25 -30 minutes on section C.

6.

Write a C program to traverse the graph of N nodes following the Depth First Search technique. (10 marks) < Answer > Write a C program to sort an array following the divide and conquer merge sort technique. Also discuss about its time complexity. (9 + 1 = 10 marks) < Answer > END OF SECTION C END OF QUESTION PAPER

7.

Suggested Answers Data Structures and Algorithm Analysis (MC211) : October 2005
Section A : Basic Concepts
1. Answer : (c) Reason: As the array can keep the data for multiple dimension values which is not possible by using any other data structure given in the question. Answer : (a) Reason: Because in Deque insertion and deletion can take place at any end, but in the question it is given as deletion is allowed only at one end. Hence it is Output restricted Deque Answer : (d) Reason: Because the reference of the next node is stored in the node itself with which one can go to next node, and hence a particular order is not required. Answer : (e) Reason: Because if the list is either small or the element is present at the mid position for the first call to the function or for the first iteration then it takes one unit of time. In worst case it takes log n time, Answer : (b) Reason: Because one can have at most one tree which is minimum, also the weights are different. Answer : (d) Reason: Because external node is a leaf node, that cant have the children Answer : (b) Reason: Because if we traverse a BST in in-order, then it is nothing but traversing in the order of increasing magnitude of their key. Answer : (c) Reason: Draw the tree according to the asked in-order and post-order and traverse the tree in preorder. Answer : (e) Reason: As this requires the traversing of nodes on the same level before traversing the nodes at next level of the tree, it requires queue. Answer : (a) Reason: Because folding is one of the method of hashing function to locate the key. Answer : (d) Reason: As in bubble sort always we swap the adjacent keys if they are not in desired order Answer : (c) Reason: Because in simple graphs the loops are not allowed. Answer : (a) Reason: Because in stack implemented using linked list, head always points to the top most node. Answer : (e) Reason: Because first = 0 and rear = size-1 means either the stack is full or it was made to empty by after filling it to full. (Since this is a circular queue). Answer : (b) Reason: As the fully parenthesized expression requires its sub parts to be in the parenthesis Answer : (e) Reason: Because the pointer is used to hold the address of the next node in the list. 6
< TOP >

2.

< TOP >

3.

< TOP >

4.

< TOP >

5. 6. 7.

< TOP >

< TOP >

< TOP >

8.

< TOP >

9.

< TOP >

10. 11. 12. 13. 14.

< TOP >

< TOP >

< TOP >

< TOP >

< TOP >

15. 16.

< TOP >

< TOP >

17.

Answer : (a) Reason: Because index is required to locate a particular position, and in arrays this index can be used to locate an element. Answer : (b) Reason: This nothing but pushing the characters on the stack and popping them from the stack and hence it will print the input in the reverse because of LIFO manner. Answer : (d) Reason: Because the answer is -18. Answer : (c) Reason: Because still the space is there in the queue and the next available location is 12th indexed one, therefore new element is inserted at that location. Answer : (a) Reason: According to the definition of the Omega notation. Answer : (e) Reason: According to the asymptotic notational rules, notation is equivalence one Answer : (b) Reason: The remaining all belongs to divide and conquer paradigm. Answer : (c) Reason: Because of the memory functions in OBST we calculate c(i, j )s, r(i, j)s and w(i , j)s. Answer : (d) Reason: According to the need of the traverse, Backtracking algorithm uses stack and Branch-andbound algorithms uses queue. Answer : (b) Reason: For any null node in the full binary tree it stores zeros. Answer : (c) Reason: According to the asymptotic notational rules. Answer : (d) Reason: According to the definition of Big Oh ( O ) Answer : (a) Reason: 1 9 2 10 3 11 4 12 5 14 8 15 6 13 7

< TOP >

18.

< TOP >

19. 20.

< TOP >

< TOP >

21. 22. 23. 24. 25.

< TOP > < TOP >

< TOP >

< TOP >

< TOP >

26. 27. 28. 29.

< TOP >

< TOP >

< TOP >

< TOP >

Accordingly the EMPTY cell is there in non shaded position and hence value of x is 0, otherwise value of x is 1. 30. Answer : (e) Reason: As there it sorts the entries in one loop. Because in nondeterministic sorting algorithms the abstractions are used which cant be programmed.
< TOP >

Section B : Problems
1. a. Algorithm : An algorithm is a set of rules for carrying out calculation ether by hand or on a machine. An algorithm is a sequence of computational steps that transform the input into the output. 7

An algorithm is a sequence of operations performed on data that have to be organized in data structures. An algorithm is an abstraction of a program to be executed on a physical machine (model of Computation).

It can also be defined as a set of computational steps to carry out a specific task. As an algorithm is a formula or set of steps for solving a particular problem, these set of rules must be unambiguous and have a clear stopping point. Algorithms can be expressed in any language, from natural languages like English to programming languages like QBASIC or SPARK. Most programs, with the exception of some artificial intelligence applications, consist of algorithms. Inventing elegant algorithms -- algorithms that are simple and require the fewest steps possible -- is one of the principal challenges in programming Characteristics of Algorithms: 1. It is composed of finite set of steps 2. Every step may have one or more statements with in it 3. It should be correct and error free 4. It should be precise and easily traceable 5. It should be rich at readability 6. It should be programming language independent 7. Focus should be on strategies and technique, but not on the declarations 8. The language used to write an algorithm must provide the data abstraction and the process abstraction too 9. It should run correctly for every set of valid data of input. 10. It should be in such a form that it can be easily converted into any programming language. The algorithms must satisfy the following constraints: 1. Input: There must be zero or more quantities that are supplied externally to the algorithm. 2. Output: On execution the algorithm must produce at least one quantity as output. 3. Definiteness: Each instruction of the algorithm must be clear and unambiguous. 4. Finiteness: The algorithm must terminate after finite number of steps. 5. Effectiveness: Every instruction in the algorithm must be in such a way that it can be carried out by a person by hand. b. For stating whether the asked equations are correct or not the following limit rules are used. i. For defining the Big Oh ( O ): Let f, g : N R be any two arbitrary functions, then the upper bound on the running time defined as
0

f (n) n g(n) lim

= = =

R+ 0

then f(n)O(g(n)) and g(n)O (f(n)) then f(n)O(g(n)) but g(n)O (f(n)) then f(n)O(g(n)) but g(n)O (f(n))
0

ii.

For defining the Theta ( ): Let f, g : N R be any two arbitrary functions, then the average running time can be defined as

f (n) n g(n) lim

= = =

R+ then f(n) (g(n)) 0 then f(n) O (g(n)) but g(n) (f(n)) then f(n) (g(n)) but g(n) (f(n))
0

iii.

For defining the Omega ( ) : Let f, g : N R be any two arbitrary functions, then to prove that f(n) (g(n)), it is enough to prove that g(n) O (f(n)) [ Duality rule] Now we will prove the following equations. i. 3n + 2 = O(n2): 8

let f(n) = 3n + 2 and g(n) = n2 then it is asked to prove f(n) O (g(n)), so we apply the limit rules as

f (n) f (n) lim n g(n) n g(n) f(n)/ g(n) = 3n+2 / n2 lim lim
=>
n

f (n) g(n) 3/2n

[ apply d/d(n) ]

f (n) n g(n) 1/n [ now apply limits ] => 3/2 lim


=> 1/ = 0 Therefore f(n)O(g(n)) but g(n)O (f(n)) And hence 3n + 2 = O(n2) is correct.

ii.

n3 + 105n2 = (n3) let f(n) = n3 + 105n2 and g(n) = n3,

then

f (n) f (n) lim n g(n) n g(n) f(n)/ g(n) = n3 + 105n2 / n3 lim lim
=>
n

f (n) g(n) n2( n + 105) / n3

=> =>

f (n) n g(n) n + 105 / n [ by applying d/d(n), then apply the limits ] lim
some real value

lim
Therefore according to limit rule

f (n) g(n) = R+ then f(n) (g(n))

And hence n3 + 105n2 = (n3) is correct. iii. 33n3 + 4n2 (n2) let f(n) = 33n3 + 4n2

and g(n) = n2,

then in order to prove

f(n) (g(n)) it is enough to prove that g(n) O (f(n)) [ Duality Rule] Hence prove that n2 O 33n3 + 4n2 Now let g(n) = 33n3 + 4n2 and f(n) = n2,

lim

f (n) f (n) lim n g(n) f(n)/ g(n) = g(n) n2 / 33n3+4n2

f (n) n g(n) 2 2 n / n (33n + 4) => lim lim f (n) n g(n) 1/ ( 33n + 4 ) [ now apply limits] =>
=> 1/ = 0 Therefore f(n)O(g(n)) but g(n)O (f(n)) Now as according to duality rule if f(n)O(g(n)) i.e., (n2)O(33n3+4n2) then g(n) ) (f(n)) i.e., (33n3 + 4n2 ) (n2) and 33n3 + 4n2 (n2) is correct now iv) and v ) can be proved following the same way where both the equations are wrong. 9

< TOP >

2.

a.

Hamiltonian graph: Let G = ( V, E ) be a connected graph with n vertices. A Hamiltonian cycle is a round-trip path along the n edges of the graph G that visits every vertex once and returns to its starting position. If a Hamiltonian cycle begins at some vertex v1G and the vertices of G are visited in the order v1, v2, , vn+1 then the edges (vi, vi+1) are in E, 1 i n, and the vi are distinct except for v1 and vn+1, which are equal Algorithm: ALGORITHM Hamiltonian ( k ) // This program uses the recursive formulation of backtracking to find all the // Hamiltonian cycles of a graph. The graph is stored as an adjacency matrix // G [ 1 .. n, 1.. n ]. All cycles begin at node 1. { repeat { // Generate values for x [ k ]. NextValue( k ); // Assign a legal next value to x [ k ]. if ( x [ k ] = 0 ) THEN return; if ( k = N ) THEN Write ( x [ 1 .. N ] ); else Hamiltonian ( k+1 ); // Probe For the Next Node } until ( false ); } ALGORITHM Next Value (k) // x [ 1 k-1] is a path of k-1 distinct vertices. If x [ k ] = 0, then no vertex has as // yet been assigned to x [ k ]. After execution x [ k ] is assigned to the next // highest numbered vertex which does not already appear in x [1 k-1 ] and is // connected by an edge to x [ k-1 ], Otherwise x [ k ]=0. If k = n, then in addition // x[k] is connected to x[1]. { repeat { x [ k ] ( x [ k ] + 1 ) mod ( n +1 ); // Next vertex if ( x [ k ] = 0 ) THEN return; if ( G [ x [ k-1 ], x [ k ] ] ) THEN { // If the edge exists for j 1 to k-1 do if ( x [ j ] = x [ k ] ) THEN break; // Check for distinctness. if ( j = k ) THEN // If true, then the vertex is distinct. if (( k < n )OR(( k = n )AND G[x [n], x[1] ] 0 ) ) THEN return; } } until ( false ); } The technique to search for an element an array following the divide and conquer rule is known as binary search. Here the same is presented using the recursive algorithm. ALGORITHM BinSearch( a, I, L, x ) // a[ I .. L ] is an array of elements in increasing order, 1 I L. x is the 10

b.

// element for search. I, L are the lower, upper bounds of the array. Algorithm // returns j such that x = a[j] if x is present in array, else returns 0 { If ( I = L ) THEN // if array is small and having only one element { If ( x = a[I] ) THEN return I; Else return 0; } Else //if it contains more than one element, then follow divide and conquer { mid ( I + L ) / 2; // Reduce a in smaller parts. If ( x = a[mid] ) THEN return mid; Else if( x < a[mid] ) THEN Return BinSearch( a, I, mid-1, x); Else Return BinSearch( a, mid+1, L, x ); } } The time complexity for this algorithm is 1 in best case as if the element is there in the mid position of the entire given list and the search is terminated in the first call to function itself or if the list is having only one element. In worst case, if the element is not there in the mid position for any call then the list is always divided into two parts and recursively the same process is repeated. And hence the time complexity can be defined as: let n be the number of elements T(n) = 1 , if list is small otherwise

T(n/2) + c.n

By solving the above one using recurrence relationship the time complexity in worst case can be defined as log n Therefore in best case it is 1, and in worst case it is log n
< TOP >

3.

a.

Dynamic Knapsack Problem: ALGORITHM Dynamic0/1knapsack (v, w, n, W) // w is the weight of each object // v is the profit associated with each of the object // n is the number of objects // W is the total capacity of the knapsack // c[1.. n,0..W] contains the maximum value that can be picked into the knapsack { 1. FOR w 0 TO W DO 2. c[ 0, w ] = 0; 3. 4. 5. 6. 7. 8. 9. FOR i 1 to n DO { c[ i, 0 ] = 0; FOR w 1 TO W DO { IF wi W THEN IF(vi + c[i-1, W - wi ] > c[ i-1, w ] ) THEN 11

10. c[ i, w ] = vi + c[ i-1, W-wi ]; 11. ELSE 12. c[ i, w ] = c[ i-1, w ]; 13. ELSE 14. c[ i, w ] = c[ i-1, w ] ; 15. } 16. } 17. } The Time complexity of this algorithm in worst case is O(nW). As the line 3 is executed for n times, and for every nth row the inner for loop (line 6) is going to be executed for W times. Hence the complexity is n*W. This is because here in this algorithm the memory table is used for the principle of optimality. b. SUM OF SUBSETS : Suppose we are given n distinct positive numbers and let m be a positive number, then the sum of sub sets problem is to find all the combinations of these numbers whose sum is m. ALGORITHM SUMOFSUBSETS( s, r, k ) // x[ 1.. n ] is a promising solution vector and is Global // The values of x[j] have already been calculated for some 1 j k // s is the summation of j numbers for some 1 j k-1 // r is the sum of remaining numbers j for some k j n // Assumption w[1] m and summation of all numbers is greater than m // m is the total sum to get { x[k] 1; //Generate left child if( s + w[k] = m ) then // subset found, also s +w[k] m as Bk-1 is TRUE write ( x [ 1 .. k ] ); else if (s + w[k] + w[k+1] m ) then SUMOFSUBSETS( s + w[k], k+1, r - w[k] ); if( s + r - w[k] ) and ( s +w[k+1] m ) then // for generating right child { x[k] 0; SUMOFSUBSETS( s, k+1, r - w[k] ); } }
< TOP >

4.

a.

Greedy Algorithms: The greedy algorithm is the most straight forward design technique to find the solution of any given problem. This algorithm works in stages, considering one input at a time. At each stage a decision is taken to see whether a particular input is in the optimal solution or not, by considering the inputs in an order determined by some selection procedure. If the inclusion of the input into the partially constructed optimal solution results into infeasible solution then the input is not added to the partial solution, otherwise it is added. ALGORITHM Greedy( A, N ) // A[1..N] is a set of elements of size N { solution // Solution set is initially empty for i 1 to N do // for all the candidate elements of set A { X SELECT( A ); // select a most feasible element in X If FEASIBLE( solution, X ) then // if X is ensuring the optimality Solution UNION( solution, X ); //add X to solution set } 12

return( solution ); } OR ALGORITHM Greedy( A ) // A is a set of candidate elements { S

// Solution set is initially empty

While ( A AND NOT solution(S) ) do { X SELECT ( A ) A A/{X} If FEASIBLE( S U {X} ) then S S U {x} } If solution(S) then return S Else Return There are no solutions } b. /* C program to evaluate a given post fix expression */

/* ***************************************************************** */ /* TITLE : POSTFIX EVALUATION */ /* AUTHOR : IMARN MD */ /* PLAT FORM : DOS VERSION 6.0, TURBO C++ COMPILER VERSION 3.0 */ /* DATE OF COMPILATION : 26 - 10 - 2004 */ /* ***************************************************************** */ # include <stdio.h> # include <math.h> # include <conio.h> /* Doesn't work with gcc compiler */ # define SIZE 20 /* SIZE OF THE STACK */ /* STACK STRUCTURE, top IS THE STACK POINTER & s[SIZE] IS ARRAY OF ELEMENTS */ typedef struct { int s[SIZE]; int top; }stack; /* stack IS NOW USER DEFINED TYPE, AND HENCE THE VARIABLES OF THIS TYPE CAN BE CREATED */ stack *p; /* INITIALIZING THE STACK AS SETTING THE STACK POINTER (top) TO -1 */ void init(stack *p) 13

{ p->top = -1; } /* OPERATOIN TO CHECK WETHER THE STACK IS FULL OR NOT - RETURNS 1 IF THE STACK IS FULL, 0 IF NOT */ int isfull(stack *p) { return( p->top >= SIZE-1); } /* OPERATOIN TO CHECK WETHER THE STACK IS EMPTY OR NOT - RETURNS 1 IF THE STACK IS EMPTY, 0 IF NOT */ int isempty(stack *p) { return( p->top == -1); } /* PUSH OPERATION TO INSERT AN ELEMENT 'x' IN A STACK POINTED BY 'p' */ void push(stack *p, int x) { if( isfull(p) ) printf("\n\tStack is full..Push operation failed. Press any KEY"); else p->s[++p->top] = x; }
/* POP OPERATION TO DELETE AN ELEMENT FROM THE STACK POINTED BY 'p'. RETURNS 32767 IF STACK IS EMPTY, OTHERWISE THE TOP ELEMENT OF THE STACK */

int pop(stack *p) { int x; if( isempty(p) ) return( 32767 ); else return( p->s[p->top--] ); } /* *********** M A I N P R O G R A M ************** */ int main() { stack a; /* 'a' STACK VARIABLE, 'p' IS A POINTER OF 'stack' TYPE */ int x, i, n1, n2; char str[SIZE]; /*CHARECTER STRING TO HOLE THE POST FIX EXPRESSION */ p = &a; clrscr(); init(p); /* INITIALIZING THE STACK POINTER 'top' */ /* MAKING 'p' TO POINT TO STACK VARIABLE 'a' */

printf("\n\t\tPlease enter a valid postfix string : "); gets(str); /* READING THE POSTFIX EXPRESSION THROUGH KEY BOARD */ 14

/* CALLING THE FUNCTION 'int value(str *)' TO GET THE RESULT OF EXPRESSION */

printf("\n\n\t\tThe Outcome Of The Given Expressoin %s Is %d", str, value(str)); printf("\n\n\t\tE N D O F T H E P R O G R A M "); getch(); return(0); } /* ************** E N D O F P R O G R A M ************** */ /* FUNCTION TO RETURN THE FINAL VALUE OF THE EXPRESSION */ int value(char *str) { int n1, n2; /* VARIABLE TO HOLD THE 2 TOP MOST REMOVED VALUES while(*str) { if( *str >= '0' && *str <='9') push(p, *str-'0'); else { n1 = pop(p); n2 = pop(p); switch(*str) { case '+' : push(p, n2+n1); break; case '-' : push(p, n2-n1); break; case '*' : push(p, n2*n1); break; case '/' : push(p, n2/n1); break; case '%' : push(p, n2%n1); break; case '@' : push(p, pow(n2,n1)); break; } } str++; } return( pop(p) ); } 5. a.

*/

< TOP >

/* The following are the tree and stack templates and are not considered for the answer of asked question */ # define SIZE 30 typedef struct treenode { struct treenode *lchild; int data; struct treenode *rchild; }tree; typedef struct stacknode { 15

int top; tree *s[SIZE]; }stack; /* Only this is the function considered for the answer */ tree *create( ) { tree *p, *l, *r, *t; stack a, *sp = &a; int x; clrscr(); init( sp ); push( sp, NULL ); t = ( tree * ) malloc( sizeof( tree ) ); p = t; printf( " \n Enter the data for ROOT : " ); scanf( "%d", &t->data ); while( p ) // p != NULL { printf( " \n Enter the data for RIGHT CHILD of NODE[ %d ], \ Press ^Z not to have ", p->data ); if( scanf( "%d", &x ) != EOF ) { r = ( tree * ) malloc( sizeof( tree ) ); r->data = x; p->rchild = r; push( sp, r ); } else p->rchild = NULL; printf( " \n Enter the data for LEFT CHILD of NODE[ %d ], \ Press ^Z not to have ", p->data ); if( scanf( "%d", &x ) != EOF ) { l = ( tree * ) malloc( sizeof( tree ) ); l->data = x; p->lchild = l; p = l; } else { p->lchild = NULL; p = pop( sp ); } } return( t ); } /* the following are the supporting functions for the code, and are not considered for the answer. These are given here only for the benefit of students */ 16

void init( stack *sp ) { sp->top = -1; } int isfull( stack *sp ) { return( sp->top == SIZE-1 ); } int isempty( stack *sp ) { return( sp->top == -1 ); } void push( stack *sp, tree *node ) { if( isfull( sp ) ) printf( " \n Stack is full " ); else sp->s[ ++sp->top ] = node; } tree *pop( stack *sp ) { tree *temp = NULL; if( isempty( sp ) ) printf( " \n Stack is empty " ); else temp = sp->s[ sp->top-- ]; return( temp ); } b. SPANNING TREE : Let G = ( N, E ) be an undirected connected graph, where N is set of nodes, E is set of edges. A sub graph T

= ( N, E`) of graph G is a Spanning Tree iff T is a tree. Also E` is sub set of E


Spanning Tree: A spanning tree is a sub graph of main graph G provided the following properties are satisfied. It should be connected. There should not be any circuits or cycles in it. Number of edges should be one les than the number of vertices.

Ex:

Number of vertices in a spanning tree is equal to number of vertices in the graph G.


0 1 2 5 3 Graph 4 3 4 Spanning tree 1 2 5 0

MINIMUM COST SPANNING TREE :

17

Given a connected, undirected graph G = <N,E> where each edge has an associated 'length' (or 'weight'). We want a subset, T, of edges, E, such that the graph remains connected if only the edges in T are used, and the sum of the lengths of edges in T is as small as possible. Such a sub graph must be a tree, and is called a Minimum Spanning Tree. Minimal Cost Spanning Tree: Start from smallest weighted edge includes this edge in the tree. Take the next smallest edge provided it does not form a cycle with already selected edges. Repeat this process until we get (n-1) edges where n is the number of vertices. A graph can have several spanning trees. If the sum of the weights is the minimal weight then such a spanning tree is called minimal cost spanning tree.

1
10

2
15 8 5

2 2
6
17

5 6

12 3

5
17

7 Weighted Graph

Minumum spanning Tree


Cost : 2+5+7+8+17 = 39

Greedy algorithm to find the minimum spanning tree. Want to find set of edges T. Start with T = EMPTY SET Keep track of connected components of graph with edges T Initially components are single nodes At each stage, add the cheapest edge that connects two nodes not already connected
< TOP >

Section C: Applied Theory


6. ///////////////////////// # include <stdio.h> # include <conio.h> # include <malloc.h> # define N 5 # define TRUE 1 # define FALSE 0 *** PROGRAM FOR DFS *** ///////////////////////

// Number of nodes

typedef struct nodeinfo // ADT for Linked List Node { int data; struct nodeinfo *next; }node; node *create( ) // Function to create a Linked List Node 18

{ int x; node *first, *temp, *t; first = ( node * ) malloc( sizeof( node ) ); first->next = NULL; temp = first; printf( "\n Enter the numbers and press ^Z to to entering \n" ); while( scanf( "%d", &x ) != EOF ) { t = ( node * ) malloc ( sizeof( node ) ); t->data = x; temp->next = t; temp = t; } temp = first; first = first->next; t->next = NULL; free( temp ); return( first ); } node **a; // To Hold The Adjacency Linked List using Mixed representation void print( node *first ) // Function to display Nodes of List { for( ; first; first = first->next ) printf( " %d ", first->data ); } void main( ) // MAIN FUNCTION { int i; void DFT( ); a = ( node **) malloc( N * sizeof( node * ) ); // Allocating space for N nodes for( i=0; i<N; i++ ) // creating the Adjacency Linked list { clrscr(); printf( " \nEnter the nodes adjacent to node %d ", i+1 ); a[i] = create(); } printf( " \n The Adjacency List is \n" ); // To display the Adjacency Linked List { printf( " \n%d---> ", i+1 ); print( a[i] ); } DFT( ); Calling the Depth First Traversing Function To Visit all the nodes getch( ); } // end of MAIN void DFS( int i, int visited[] ) // Depth First Search Function 19

for( i=0; i<N; i++ )

{ node *temp; if( !visited[i] ) // If the node(vertex) is not visited { printf( " \n %d is visited ", i+1 ); // Print to show it is visited visited[i] = TRUE; // visit the node by marking as TRUE for( temp = a[i]; temp; temp = temp->next ) // Visit all adjacent nodes if( !visited[temp->data] )

// If this adjacent node is not visited DFS( temp->data, visited ); // Recursive call to visit the adjacent // nodes of temp->data pointed vertex

} } void DFT( ) Depth First Traversing Function { int visited[N]; // Array to keep track of which node is visited int i; for( i = 0; i < N; i++ ) visited[i] = FALSE; // Initially No any node is visited for( i = 0; i < N; i++ ) if( !visited[i] ) // if not vivited, then visit it DFS( i, visited ); } < TOP > 7. # include <stdio.h> # include <conio.h> # define size 15 void merge( int a[], int low, int mid, int high ) { int i, j, k, l; int b[size]; l = k = low; j = mid + 1; while( ( l <= mid ) && ( j <= high ) ) if( a[l] <= a[j] ) b[k++] = a[l++]; else b[k++] = a[j++]; if( l > mid ) for( i = j; i <= high; i++ ) b[k++] = a[i]; else for( i = l; i <= mid; i++ ) b[k++] = a[i]; 20

for( i = low; i <= high; i++ ) a[i] = b[i]; } void dcmergesort( int a[], int low, int high ) { int mid; if( low < high ) { mid = ( low + high ) / 2; dcmergesort( a, low, mid ); dcmergesort( a, mid+1, high ); merge( a, low, mid, high ); } }

void main() { int a[size], i; clrscr(); for( i=0; i<size; i++ ) { printf( "\n Please enter %d element", i+1 ); scanf( "%d", &a[i] ); } printf( "\n The elements you entered are \n" ); for( i=0; i<size; printf( "%4d", a[i++] ) ); dcmergesort( a, 0, size-1 ); printf( "\n The sorted elements are \n" ); for( i=0; i<size; printf( "%4d", a[i++] ) ); getch(); } The above algorithm follows divide and conquer rule and hence every time the list is divided in to parts and the sub parts are sorted individually and finally the two sorted parts are merged together to get the total sorted list. The process of division and merging is repeated till there is more than one element, and the process of division stops when there is only one element in any part. Hence the time complexity can be derived as : let n be the number of elements in the list, then 21

T(n) =

1 2T(n/2) + c.n

, if n = 1 , otherwise

By solving the above one using recurrence relationship we obtain the worst time complexity as n. log n And hence in all the cases the algorithm takes O(n. log n) time.
< TOP >

< TOP OF THE DOCUMENT >

22

Você também pode gostar