Sei sulla pagina 1di 77

MASTER OF COMPUTER APPLICATIONS

IV SEMESTER
10MCA 48 Algorithms LAB

Compiled by: Prof S.Anupamakumar Chandrashekhar B

Dept of MCA,RVCE

INDEX

S.No 1 2 3 4 5 6

Content List of Lab Programs Dos and Donts in the Lab Solutions to Lab Programs Extra Questions Viva Questions Lab Cycles and Procedure for record writing

Page No 4 6 8 73 74 76

Dept of MCA,RVCE

LAB PROGRAMS

Dept of MCA,RVCE

Dept of MCA,RVCE

Dept of MCA,RVCE

Dos and Dont in the Laboratory


DO ..

Come prepared to the Lab. Submit your Records to the Lecturer and sign in the Log Book on entering the Lab. Follow the Lab exercise cycles as instructed by the Department. Violating the same will result in deduction of marks. Use the same login assigned to you. Put the chairs back to its position before you leave. Backlog exercises should be executed after completing regular exercises.

DONT ..

Move around in the lab during the lab session. Tamper System Files or Try to access the Server. Write Data Sheets or Records in the Lab. Change the system assigned to you without the notice of the Lab Staff. Teaching your friends.

Dept of MCA,RVCE

SOLUTIONS

Dept of MCA,RVCE

INDEX

SL. No. 1.

CONTENT
Sort a given set of elements using the Quick sort method and determine the time required to sort the elements. Repeat the experiment for different values of n, the number of elements in the list to be sorted and plot a graph of the time taken versus n. The elements can be read from a file or can be generated using the random number generator. Using OpenMP, implement a parallelized Merge Sort algorithm to sort a given set of elements and determine the time required to sort the elements. Repeat the experiment for different values of n, the number of elements in the list to be sorted and plot a graph of the time taken versus n. The elements can be read from a file or can be generated using the random number generator. a. Obtain the Topological ordering of vertices in a given digraph. b. Compute the transitive closure of a given directed graph using Warshall's algorithm Implement 0/1 Knapsack problem using Dynamic Programming. From a given vertex in a weighted connected graph, find shortest paths to other vertices using Dijkstra's algorithm Find Minimum Cost Spanning Tree of a given undirected graph using Kruskal's algorithm. a. Print all the nodes reachable from a given starting node in a digraph using BFS method. b. Check whether a given graph is connected or not using DFS method. Find a subset of a given set S = {sl,s2,.....,sn} of n positive integers whose sum is equal to a given positive integer d. For example, if S= {1, 2, 5, 6, 8} and d = 9 there are two solutions{1,2,6}and{1,8}.A suitable message is to be displayed if the given problem instance doesn't have a solution.

Page No 8

2.

18

3.

27

4. 5. 6. 7.

31 34 38 43

8.

51

Dept of MCA,RVCE

9.

Implement any scheme to find the optimal solution for the Traveling Salesperson problem and then solve the same problem instance using any approximation algorithm and determine the error in the approximation.

53

10 Find Minimum Cost Spanning Tree of a given undirected graph using Prims algorithm. . 11 Implement All-Pairs Shortest Paths Problem using Floyd's algorithm. Parallelize this algorithm, implement it using .
OpenMP and determine the speed-up achieved.

59 63

12 Implement N Queen's problem using Back Tracking. .

69

Dept of MCA,RVCE

1. Sort a given set of elements using Quick Sort method. Determine the time required to sort the elements. Repeat the experiment for different values of n, the number of elements in the list to be searched and plot a graph of the time taken versus n. The elements can be read from a file or can be generated using the random number generator.

Quick Sort
Problem: To sort a set of elements and determine the time required to sor the elements. Method : It is used on the principle of divide-and-conquer method. Quick sort works by partitioning a given array A[p . . r] into two non-empty sub array A[p . . q] and A[q+1 . . r] such that every key in A[p . . q] is less than or equal to every key in A[q+1 . . r]. Then the two sub arrays are sorted by recursive calls to Quick sort. The exact position of the partition depends on the given array and index q is computed as a part of the partitioning procedure.
Advantages:
It requires otnly n log (n) time to sort n items. It has an extremely short inner loop

Dis advantages

It is recursive. Especially if recursion is not available, the implementation is extremely complicated. It requires quadratic (i.e., n2) time in the worst-case. It is fragile i.e., a simple mistake in the implementation can go unnoticed and cause it to perform badly.

Procedure for Quick sort Quick Sort If p < r then q Partition (A, p, r) Dept of MCA,RVCE 10

Recursive call to Quick Sort (A, p, q) Recursive call to Quick Sort (A, q + r, r) Source Code #include<stdio.h> #include<sys/time.h> #include<stdlib.h> #define MAX 1000 struct Timer { int limit; int time; }mytimer[10]; void quicksort(int a[],int low,int high) { int j; if(low<high) { j=partition(a,low,high); quicksort(a,low,j-1); quicksort(a,j+1,high); } } int partition(int a[],int low,int high) { int i,j,temp,key; key=a[low]; i=low+1; j=high; while(1) { Dept of MCA,RVCE 11

while(i<high && key>=a[i]) i++; while(key<a[j]) j--; if(i<j) { temp=a[i]; a[i]=a[j]; a[j]=temp; } else { temp=a[low]; a[low]=a[j]; a[j]=temp; return j; } } } int main(int argc, char ** argv) { int i,n,a[MAX],k; struct timeval st,en; printf("----------------------------\n Loop will Run MAX 10 Times (To break press zero(0)\n----------------------\n"); for(k=0;k<10;k++) { printf("\nEnter the number of elements\n"); scanf("%d",&n); if(n<=0) break; Dept of MCA,RVCE 12

switch(argc) { case 2:for(i=0;i<n;i++){ a[i]=rand()% 1000; printf(" %5d ",a[i]); } break; default:printf("\n Enter %d Elements \n ",n); for(i=0;i<n;i++) scanf("%d",&a[i]); } gettimeofday(&st,0); quicksort(a,0,n-1); gettimeofday(&en,0); printf("\n The Sorted array is \n"); for(i=0;i<n;i++) printf("%d\t",a[i]); printf("\nTime taken= %d Micro Seconds",mytimer[k].time=(en.tv_usec-st.tv_usec)); mytimer[k].limit=n; } printf("\n Data Limit for(k--;k>=0;k--) printf("%5d %5d \n",mytimer[k].limit,mytimer[k].time); return 0; } Time taken\n");

Enter the number of elements 10 Dept of MCA,RVCE 13

383 886 777 915 The Sorted array is

793

335

386 649

492 777

649 793

421 886 915

335 383 386 421 492 Time taken= 3 Micro Seconds Enter the number of elements 100 362 27 690 59 763 926 530 862 123 67 135 929 229 373 421 919 784 537 873 862 170 996 281 305 124 895 582 545 814 367 584 403 651 754 399 932 795 570 434 378 467 601 The Sorted array is 11 12 22 87 91 198 211 327 336 399 403 505 526 586 601 782 784 873 895 27 94 226 362 413 530 651 788 902 42 97 229 364 421 537 676 795 919

540 802 198 925 434 60 97 43 123 276 367 426 539 690 802 925

426 22 324 84 364 676 902 58 124 281 368 429 540 729 808 926

172 58 315 327 43 368 317

736 69 370 336 750 739 492

211 167 413 505 87 12

368 393 526 846 808 226

567 456 91 729 276 586

429 11 980 313 178 94

782 42 956 857 788 539

59 135 305 368 434 545 736 814 929

60 167 313 370 434 567 739 846 932

67 170 315 373 456 570 750 857 956

69 172 317 378 467 582 754 862 980

84 178 324 393 492 584 763 862 996

Time taken= 15 Micro Seconds Enter the number of elements 1000 652 756 301 280 286 441 771 481 675 709 927 567 528 871 732 829 503 19 245 846 451 921 555 379 124 914 987 856 743 491 407 474 121 858 395 29 776 404 443 763 613 538 996 324 743 470 183 490 669 82 542 464 197 507 568 340 422 311 810 605 522 465 708 416 282 258 550 468 71 973 131 881 959 773 813 668 190 95 Dept of MCA,RVCE

865 856 270 488 227 237 606 499 355 801 924 930 926

689 497 368 764 365 235 840 772 804 661 637 933 466

444 353 708 228 859 793 904 725 348 730 62 894 84

619 586 715 841 936 818 818 644 611 878 624 660 340

440 965 340 350 432 428 128 590 622 305 600 163 90

729 306 149 193 551 143 688 505 828 320 36 199 684

31 683 796 500 437 11 369 139 299 736 452 981 376

117 219 723 34 228 928 917 954 343 444 899 899 542

97 624 618 764 275 529 917 786 746 626 379 996 936 14

107 445 756 179 418 887 412 348 172 659 206 301 713 372 321 255 819 599 721 904 228 127 150 984 658 920 224 422 269 396 672 850 625 385 222 299 640 42 898 713 581 819 336 732 155 994 4 379 769 273 579 884 993 205 621 567 504 613 961 754 506 784 21 842 868 528 189 872 908 958 303 333 133 648 890 754 567 746 368 529 990 303 33 363 497 253 892 686 125 152 436 460 414 921 460 304 28 27 50 748 43 39 2 428 403 500 681 647 538 159 215 127 504 629 49 964 285 429 343 335 289 367 988 292 795 743 144 829 390 682 261 42 360 117 23 761 81 309 190 425 626 524 57 614 168 205 358 312 386 100 578 529 946 290 647 970 51 80 631 593 355 512 90 412 479 610 969 189 274 355 338 566 770 284 856 417 606 260 849 237 783 873 458 873 637 289 483 607 478 757 618 438 25 388 74 233 157 681 493 358 363 622 794 173 847 431 462 682 390 292 574 491 947 951 231 21 537 740 54 30 2 231 139 796 404 338 580 218 21 970 536 904 176 483 207 759 857 744 499 911 105 563 49 244 711 805 934 291 375 955 805 882 822 982 717 30 93 574 126 593 713 179 377 762 775 88 919 710 732 294 153 943 573 328 925 291 710 18 217 836 904 571 661 633 685 789 73 604 851 805 195 639 949 120 967 226 763 677 596 981 518 211 342 532 196 379 321 270 984 172 398 830 63 347 950 30 573 714 59 522 204 954 443 898 486 640 278 159 262 262 272 122 154 335 821 457 365 747 171 776 933 907 959 728 806 797 720 84 308 334 52 171 189 559 506 10 16 224 109 539 114 338 989 426 67 147 223 787 231 532 590 254 350 131 813 857 494 181 81 603 415 296 825 404 722 892 551 297 32 134 595 999 962 297 483 776 154 977 309 587 860 682 211 685 86 285 930 990 583 314 528 839 525 490 136 360 618 643 337 928 225 815 570 437 853 8 722 783 350 657 651 149 910 528 639 398 888 610 393 577 87 777 99 657 566 952 17 641 735 368 Dept of MCA,RVCE

9 939 81 298 776 326 498 500 996 556 151 177 340 996 346 857 641 205 314 270 791 98 862 127 614 486 17 963 250 865 427 47 683 269 698 0 122 720 181 932 476 582 97 890 298

336 811 630 190 850 259 36 46 975 902 535 900 541 367 726 627 620 59 471 699 57 325 812 950 589 253 346 55 868 560 234 924 41 218 991 378 281 433 506 382 116 621 827 976 184

210 940 84 524 255 944 808 788 188 794 134 238 569 677 994 312 433 217 729 417 115 81 379 236 768 543 235 90 503 36 40 82 848 701 376 109 875 982 415 21 820 310 126 199 195

342 667 292 590 860 202 753 797 157 697 339 971 826 234 916 886 987 518 100 839 521 516 977 560 993 74 137 858 485 955 283 435 723 703 898 53 850 181 57 266 892 955 269 552 776

587 705 972 209 142 202 248 249 729 699 692 949 232 690 552 214 888 945 459 569 157 516 685 818 918 814 691 130 6 770 72 232 324 653 715 81 179 487 708 563 525 888 71 931 805 15

266 428 954 528 308 283 412 127 382 421 762 972 541 716 852 364 790 263 491 172 970 352 665 511 69 489 32 154 104 875 649 814 465 314 326 109 631 673 264 735 468 156 960 933 823 The Sorted array is 0 2 2 17 17 18 28 29 30 36 36 37 47 49 49 57 59 59 74 74 80 84 84 84 97 97 98 109 112 114 124 125 126 131 133 134 143 144 147 154 154 154 159 163 168 173 176 177 184 188 189 196 197 197 205 206 207 217 218 218 228 228 228 235 235 236 253 253 254 263 264 266 273 274 275 284 285 285 292 292 292 299 300 301 309 309 310 321 321 324 334 334 335 340 340 340 347 348 348 355 355 355 Dept of MCA,RVCE

593 693 850 37 517 679 886 548 286 4 19 30 39 50 62 81 86 99 115 126 134 149 155 170 179 189 198 209 219 231 237 255 266 278 286 294 301 311 324 335 340 350 358

278 334 662 537 361 141 183 295 171 6 21 30 39 51 63 81 87 100 116 127 136 149 155 171 179 189 199 210 222 231 237 255 269 278 286 295 303 312 325 336 341 350 358

197 439 482 859 83 412 39 877 358 8 21 31 40 52 67 81 88 100 117 127 137 150 156 171 179 190 199 211 223 231 238 258 269 280 289 296 303 312 325 336 342 350 358

555 334 399 828 351 538 969 313 677

672 421 217 871 112 969 535 833 140

774 159 154 280 300 636 152 198

445 985 173 987 506 170 621 949

0 957 15 856 638 956 393 355

325 354 506 590 667 844 790 155

997 761 851 341 364 760 289 793

9 21 32 41 53 69 81 90 104 117 127 139 151 157 171 181 190 202 211 224 232 244 259 269 280 289 297 304 313 326 337 342 351 360

10 21 32 42 54 71 81 90 105 120 127 139 152 157 172 181 190 202 214 224 232 245 260 270 281 289 297 305 314 326 338 343 352 360

11 23 33 42 55 71 82 90 107 121 128 140 152 157 172 181 193 204 215 225 233 248 261 270 282 290 298 306 314 328 338 343 353 361

15 25 34 43 57 72 82 93 109 122 130 141 153 159 172 183 195 205 217 226 234 249 262 270 283 291 298 308 314 333 338 346 354 363

16 27 36 46 57 73 83 95 109 122 131 142 154 159 173 183 195 205 217 227 234 250 262 272 283 291 299 308 320 334 339 346 355 363 16

364 375 382 398 414 425 435 444 464 479 489 499 506 518 528 537 550 563 571 583 593 610 620 627 639 651 665 677 685 699 711 721 730 744 759 769 776 790 801 813 821 833 849 856 862

364 376 385 399 415 426 436 445 465 481 490 499 506 521 528 538 551 563 573 586 595 610 621 629 640 652 667 679 685 699 713 722 732 746 760 770 776 791 804 813 822 836 850 856 865

365 376 386 403 415 427 437 445 465 482 490 500 506 522 529 538 551 566 573 587 596 611 621 630 640 653 667 681 686 701 713 722 732 746 761 770 777 793 805 814 823 839 850 857 865

365 377 388 404 416 428 437 451 466 483 491 500 506 522 529 538 552 566 574 587 599 613 621 631 641 657 668 681 688 703 713 723 732 747 761 771 783 793 805 814 825 839 850 857 868

367 378 390 404 417 428 438 452 468 483 491 500 507 524 529 539 552 567 574 589 600 613 622 631 641 657 669 682 689 705 714 723 735 748 762 772 783 794 805 815 826 840 850 857 868

367 379 390 404 417 428 439 457 468 483 491 503 511 524 532 541 555 567 577 590 603 614 622 633 643 658 672 682 690 708 715 725 735 753 762 773 784 794 805 818 827 841 851 858 871

368 379 393 407 418 429 440 458 470 485 493 503 512 525 532 541 555 567 578 590 604 614 624 636 644 659 672 682 691 708 715 726 736 754 763 774 786 795 806 818 828 842 851 858 871

368 379 393 412 421 431 441 459 471 486 494 504 516 525 535 542 556 568 579 590 605 618 624 637 647 660 673 683 692 708 716 728 740 754 763 775 787 796 808 818 828 844 852 859 872

368 379 395 412 421 432 443 460 474 486 497 504 516 528 535 542 559 569 580 590 606 618 625 637 647 661 675 683 693 709 717 729 743 756 764 776 788 796 810 819 829 846 853 859 873

369 379 396 412 422 433 443 460 476 487 497 505 517 528 536 543 560 569 581 593 606 618 626 638 648 661 677 684 697 710 720 729 743 756 764 776 789 797 811 819 829 847 856 860 873

372 382 398 412 422 433 444 462 478 488 498 506 518 528 537 548 560 570 582 593 607 619 626 639 649 662 677 685 698 710 720 729 743 757 768 776 790 797 812 820 830 848 856 860 875 17

Dept of MCA,RVCE

875 888 899 914 925 933 949 955 964 972 984 993

877 890 900 916 926 934 949 955 965 973 985 994

878 890 902 917 927 936 949 956 967 975 987 994

881 892 904 917 928 936 950 957 969 976 987 996

882 892 904 918 928 939 950 958 969 977 987 996

884 892 904 919 930 940 951 959 969 977 988 996

886 894 904 920 930 943 952 959 970 981 989 996

886 898 907 921 931 944 954 960 970 981 990 997

887 898 908 921 932 945 954 961 970 982 990 999

888 898 910 924 933 946 954 962 971 982 991

888 899 911 924 933 947 955 963 972 984 993

Time taken= 182 Micro Seconds Enter the number of elements 0 Data Limit 1000 100 10 Time taken 182 15 3

2. Using OpenMP, implement a parallelized Merge Sort algorithm to sort a given set of elements and determine the time required to sort the elements. Repeat the experiment for different values of n, the number of elements in the list to be sorted and plot a graph of the time taken versus n. The elements can be read from a file or can be generated using the random number generator. Problem : To sort a given set of records using merge sort. The program should use openMP to parallelize the mergesort. Method : Merge Sort 3. Merge-sort is based on the divide-and-conquer paradigm. The Merge-sort algorithm can be described in general terms as consisting of the following three steps: 4. 1. Divide Step 5. If given array A has zero or one element, return S; it is already sorted. Otherwise, divide A into two arrays, A1 and A2, each containing about half of the elements of A. 6. 2. Recursion Step

Dept of MCA,RVCE

18

7. Recursively sort array A1 and A2. 8. 3. Conquer Step 9. Combine the elements back in A by merging the sorted arrays A1 and A2 into a sorted sequence. 10. Merge sort has a guaranteed

n log n running time. Meaning merge sort

works 11.n log n in worst, best and average cases.


To begin, suppose that we have two sorted arrays A1[1], A1[2], . . , A1[M] and A2[1], A2[2], . . . , A2[N]. The following is a direct algorithm of the obvious strategy of successively choosing the smallest remaining elements from A1 to A2 and putting it in A. Open MP OpenMP is an Application Program Interface (API), jointly defined by a group of major computer hardware and software vendors. OpenMP provides a portable, scalable model for developers of shared memory parallel applications. The API supports C/C++ and Fortran on a wide variety of architectures. Open MP Model: 1. Shared Memory, Thread Based Parallelism: OpenMP is based upon the existence of multiple threads in the shared memory programming paradigm. A shared memory process consists of multiple threads. 2. Explicit Parallelism: OpenMP is an explicit (not automatic) programming model, offering the programmer full control over parallelization. 3. Fork - Join Model:

OpenMP uses the fork-join model of parallel execution:

List of Open MPFunctions Used in Mergesort: 1. #include<omp.h> : It is the header file which should be used to implement the functions using open MP 2.#pragma omp parallel private(var1, var2) shared(var3) { Parallel section executed by all threads Dept of MCA,RVCE 19

. . . All threads join master thread and disband } This section is used to parallelize all the sections using threds. 3. #pragma omp sections nowait : Helps to define the progam using different sections so that it can be run parallely. Execution : To execute programs using open MP concepts the command is gcc -fopenmp filename.c Procedure: MERGE (A1, A2, A) i. j 1 A1[m+1], A2[n+1] INT_MAX For k 1 to m + n do if A1[i] < A2[j] then A[k] A1[i] i i +1 else A[k] A2[j] jj+1 Merge Sort Algorithm MERGE_SORT (A) A1[1 . . n/2 ] A[1 . . n/2 ] n/2 . . n] A2[1 . . n/2 ] A[1 + Merge Sort (A1) Merge Sort (A1) Merge Sort (A1, A2, A) Source Code #include<stdio.h>

Dept of MCA,RVCE

20

#include<sys/time.h> #include<omp.h> #include<stdlib.h> #define MAX 1000 struct Timer { int limit; int time; }mytimer[10]; void mergesort(int ar[], int,int); void merge(int [], int,int,int); int main(int argc,int argv) { int a[MAX],i,n,k,g; struct timeval st,en; printf(" Loop will run MAX 10 times ( to break press zero\n"); for(k=0;k<10;k++) { printf("\n enter the number of elements\n"); scanf("%d",&n); if(n<=0) break; switch(argc) Dept of MCA,RVCE 21

{ case 2: for(i=0;i<n;i++) { a[i]=rand()% MAX; printf("%5d",a[i]); } break; default : printf("Enter %d Elements\n",n); for(i=0;i<n;i++) scanf("%d",&a[i]); } gettimeofday(&st,0); mergesort(a,0,n-1); gettimeofday(&en,0); printf("\n The sorted array is \n"); for(i=0;i<n;i++) printf("%d\t",a[i]); printf("\nTime taken = mytimer[k].limit=n; } printf("\n Data Limit for(k--;k>=0;k--) Time Taken \n"); %d Micro seconds ",mytimer[k].time=(en.tv_usec-st.tv_usec));

Dept of MCA,RVCE

22

printf("%5d return 0; }

%5d \n",mytimer[k].limit,mytimer[k].time);

void mergesort(int a[], int low, int high) { int mid; if(low < high) { mid = (low+high)/2; mergesort(a,low,mid); mergesort(a,mid+1,high); merge(a,low,mid,high); } } void merge(int a[], int low, int mid, int high) { int i,j,h,k,b[MAX]; int nthreads,tid; #pragma omp parallel shared(a,low,mid,high,nthreads) private(i,tid) { tid=omp_get_thread_num(); if (tid==0) {

Dept of MCA,RVCE

23

nthreads=omp_get_num_threads(); printf("number of threads %d\n",nthreads); } printf("thread %d starting \n",tid); #pragma omp sections nowait { printf("thread %d doing section 1 \n",tid); h=i=low; j=mid+1; //for (h=low,j=mid+1;h<=mid,j<=high;h++,j++) while (h<=mid && j<=high) { if(a[h] < a[j]) { b[i++] = a[h++]; } else { b[i++] = a[j++]; } } #pragma omp section { Dept of MCA,RVCE 24

if(h>mid) { for(k=j;k<=high;k++) b[i++] = a[k]; } else { for(k=h;k<=mid;k++) b[i++]=a[k]; }} #pragma omp section { for(k=low;k<=high;k++) a[k]=b[k]; printf ("thread in section 2 %d\n",tid); }}}} Output: ./a.out 1 Loop will run MAX 10 times ( to break press zero enter the number of elements 10 383 886 777 915 793 335 386 492 649 421number of threads 4 thread 0 starting Dept of MCA,RVCE 25

thread 0 doing section 1 thread in section 2 0 thread 1 starting thread 2 starting thread 3 starting thread 2 starting thread 2 doing section 1 thread in section 2 2 thread 1 starting number of threads 4 thread 0 starting thread 3 starting thread 2 starting thread 2 doing section 1 thread in section 2 2 thread 1 starting number of threads 4 thread 0 starting thread 3 starting thread 2 starting thread 2 doing section 1 thread in section 2 2

Dept of MCA,RVCE

26

thread 1 starting number of threads 4 thread 0 starting thread 3 starting thread 2 starting thread 2 doing section 1 thread in section 2 2 thread 3 starting thread 1 starting number of threads 4 thread 0 starting thread 2 starting thread 2 doing section 1 thread in section 2 2 thread 1 starting number of threads 4 thread 0 starting thread 3 starting thread 2 starting thread 2 doing section 1 thread in section 2 2 thread 1 starting number of threads 4 Dept of MCA,RVCE 27

thread 0 starting thread 3 starting thread 2 starting thread 2 doing section 1 thread in section 2 2 thread 1 starting number of threads 4 thread 0 starting thread 3 starting thread 2 starting thread 2 doing section 1 thread in section 2 2 thread 1 starting number of threads 4 thread 0 starting thread 3 starting The sorted array is 335 383 386 421 492 649 777 793 886 915

Time taken = 1334 Micro seconds enter the number of elements 5 362 27 690 59 763number of threads 4

Dept of MCA,RVCE

28

thread 0 starting thread 0 doing section 1 thread in section 2 0 thread 1 starting thread 2 starting thread 3 starting thread 1 starting thread 1 doing section 1 thread in section 2 1 thread 3 starting thread 2 starting number of threads 4 thread 0 starting thread 2 starting thread 2 doing section 1 thread in section 2 2 thread 1 starting number of threads 4 thread 0 starting thread 3 starting thread 2 starting thread 2 doing section 1 thread in section 2 2 Dept of MCA,RVCE 29

thread 1 starting number of threads 4 thread 0 starting thread 3 starting The sorted array is 27 59 362 690 763

Time taken = 59360 Micro seconds enter the number of elements 0 Data Limit 5 10 Time Taken 59360 1334

3a.Obtain the Topological ordering of vertices in a given digraph. Problem: To order/sort the given vertices of a given digraph Method: A cycle in a diagraph or directed graph G is a set of edges, {(v1, v2), (v2, v3), ..., (vr 1, vr)} where v1 = vr. A diagraph is acyclic if it has no cycles. Such a graph is often referred to as a directed acyclic graph, or DAG, for short. This uses the basic traversal techniques to order the vertices Procedure: The topological ordering is done using : for(i=0;i<n;i++) for(j=0;j<n;j++) indeg[i]=indeg[i]+a[j][i]; while(count<n) Dept of MCA,RVCE 30

{ for(k=0;k<n;k++) { if((indeg[k]==0) && (flag[k]==0)) { printf("%d,,(k+1)); flag [k]=1; } for(i=0;i<n;i++) { if(a[i][k]==1) indeg[k]--; } } count++; } Source Code: #include <stdio.h> #include <stdlib.h> # include <math.h> int main() { int i,j,k,n,a[10][10],indeg[10],flag[10],count=0; printf("Enter the no of vertices:"); scanf("%d",&n); printf("Enter the adjacency matrix:"); for(i=0;i<n;i++) for(j=0;j<n;j++) scanf("%d",&a[i][j]); for(i=0;i<n;i++) { indeg[i]=0; flag[i]=0; } for(i=0;i<n;i++) for(j=0;j<n;j++) indeg[i]=indeg[i]+a[j][i]; printf("The topological order is:"); while(count<n) { Dept of MCA,RVCE 31

for(k=0;k<n;k++) { if((indeg[k]==0) && (flag[k]==0)) { printf("%d",(k+1)); flag [k]=1; } for(i=0;i<n;i++) { if(a[i][k]==1) indeg[k]--; } } count++; } return 0; } Enter the no of vertices:4 Enter the adjacency matrix: 0110 0010 0010 0000 The topological order is : 1234 3 b. Compute the transitive closure of a given directed graph using Warshalls algorithm. Warshalls algorithm is used to find the transitive closure of a directed graph. This is the application of dynamic programming technique. Transitive Closure Transitive closure of an directed graph with n vertices can be defined as the n-by-n Boolean matrix T={tij} in which the element in the ith row (1in) and the jth column (1jn) is 1 if there exists a nontrivial directed path( a directed path of a positive length) from ith vertex to the jth vertex otherwise tij is 0.

Dept of MCA,RVCE

32

Warshall's Algorithm Warshall (int N, bmatrix &A, bmatrix &P) { int i,j,k; for (i = 0; i < N; i++) for (j = 0; j < N; j++) /* There's a path if there's an edge */ P[i][j] = A[i][j]; for (k = 0; k < N; k++) for (i = 0; i < N; i++) for (j = 0; j < N; j++) if (! P[i][j]) P[i][j] = P[i][k] && P[k][j]; } /* Warshall */ Source Code: #include<stdio.h> #define MAX 10 void warshall(int p[10][10],int n); void main() { int p[10][10],i,j,n; printf("\n Enter the number of vertices\n :"); scanf("%d",&n); printf("Enter adj mattrix ..\n"); for(i=1;i<=n;i++) for (j=1;j<=n;j++) scanf("%d",&p[i][j]); warshall(p,n); for(i=1;i<=n;i++) { for (j=1;j<=n;j++) printf("\t%d",p[i][j]); printf("\n"); } } void warshall(int p[10][10],int n) { int i,j,k; Dept of MCA,RVCE 33

for(k=1;k<=n;k++) for(i=1;i<=n;i++) if(p[i][k]==1) for (j=1;j<=n;j++) p[i][j]=p[i][j] || p[k][j]; } Enter the number of vertices :4 Enter adj mattrix .. 0 0 0 1 100 001 000 010

Transitive closure(Path Matrix) is 111 1 1 111 0 000 1 11 1 4. Implement 0/1 Knapsack problem using dynamic programming. knapsack problem We have a knapsack that has capacity (weight) C and have several items I1,,In.Each item Ij has a weight wj and a benefit bj.we want to place a certain number of copies of each item Ij in the knapsack so that:(i)The knapsack weight capacity is not exceeded and (ii)The total benefit is maximal. Method: A greedy optimal solution can be used to solve the knapsack problem. Procedure: int knapsack(int i,int m) { if(i==n) return(m<w[n])?0:p[n]; if(m<w[i])

Dept of MCA,RVCE

34

return knapsack(i+1,m); return maxi(knapsack(i+1,m),knapsack(i+1,m-w[i])+p[i]); } Source Code: #include<stdio.h> #define max 30 #define true 1 #define false 0 int knapsack(int,int); int maxi(int,int); int p[max]; int w[max]; int n; int main() { int m,cu,optsoln, i; printf("Enter the no. of Objects:\n"); scanf("%d",&n); printf("Enter the weights:\n"); for(i=1;i<=n;i++) scanf("%d",&w[i]); printf("Enter the profits:\n"); for(i=1;i<=n;i++) Dept of MCA,RVCE 35

scanf("%d",&p[i]); printf("Enter the knapsack capacity:"); scanf("%d",&m); printf("\nWeights Profits"); for(i=1;i<=n;i++) printf("\n%5d %13d",w[i],p[i]); printf("\nKnapsack capacity %3d",m); optsoln=knapsack(1,m); printf("\n\nOptimal solution = %d\n",optsoln); } int knapsack(int i,int m) { if(i==n) return(m<w[n])?0:p[n]; if(m<w[i]) return knapsack(i+1,m); return maxi(knapsack(i+1,m),knapsack(i+1,m-w[i])+p[i]); } int maxi(int a,int b) { if(a>b) return a; else return b;

Dept of MCA,RVCE

36

} Enter the no. of Objects: 4 Enter the weights: 2 1 32 Enter the profits: 12 10 20 15 Enter the knapsack capacity:5 Weights Profits 2 1 3 12 10 20

2 15 Knapsack capacity 5 Optimal solution = 37 5. From a given vertex in a weighted connected graph, find shortest paths to other vertices using Dijkstras algorithm. Problem Considering a directed graph G = (V, E). Determine the length of the shortest path from the source to each of the other nodes of the graph. This problem can be solved by a greedy algorithm often called Dijkstra's algorithm. Method: The algorithm maintains two sets of vertices, S and C. At every stage the set S contains those vertices that have already been selected and set C contains all the other vertices. Hence we have the invariant property V=S U C. When algorithm starts Delta contains only the source vertex and when the algorithm halts, Delta contains all the vertices of the graph and problem is solved. At each step algorithm choose the vertex in C whose distance to the source is least and add it to S. Procedure: Void shortestpath(int v,int cost[][MAX],int dist[],int n) { Dept of MCA,RVCE 37

int s[MAX]; int u,i,j,w,num; for(i=1;i<=n;i++) { s[i]=FALSE; dist[i]=cost[v][i]; } s[v]=TRUE; dist[v]=1; num=2; while(num<=n) { u=choose(dist,s,n); s[u]=TRUE; num++; for(w=1;w<=n;w++) { if(((dist[u]+cost[u][w])<dist[w]) && !s[w]) dist[w]=dist[u]+cost[u][w]; } } } Source Code #include<stdio.h> #define MAX 10 #define TRUE 1 #define FALSE 0 #define INFINITY 9999 void shortestpath(int,int [][MAX],int [],int); int choose(int [],int [],int); Dept of MCA,RVCE 38

void main() { int cost[MAX][MAX]; int dist[MAX]; int i,j,n; int v; printf("Enter the no. of vertices:"); scanf("%d",&n); printf("Enter the cost matrix(row wise)\n"); printf("-Enter 9999 for noedge or INFINITY \n"); for(i=1;i<=n;i++) for(j=1;j<=n;j++) scanf("%d",&cost[i][j]); printf("Enter the starting node:"); scanf("%d",&v); shortestpath(v,cost,dist,n); printf("Shortest path from starting node to Destination Node is as shown below\n"); printf("Destination Node for(j=1;j<=n;j++) if(j!=v) printf("%15d } void shortestpath(int v,int cost[][MAX],int dist[],int n) { int s[MAX]; int u,i,j,w,num; for(i=1;i<=n;i++) { | %5d\n",j,dist[j]); | Distance\n");

Dept of MCA,RVCE

39

s[i]=FALSE; dist[i]=cost[v][i]; } s[v]=TRUE; dist[v]=1; num=2; while(num<=n) { u=choose(dist,s,n); s[u]=TRUE; num++; for(w=1;w<=n;w++) { if(((dist[u]+cost[u][w])<dist[w]) && !s[w]) dist[w]=dist[u]+cost[u][w]; } } } int choose(int dist[],int s[],int n) { int w,j=1,min; min=INFINITY; for(w=1;w<=n;w++) { if((dist[w]<min) && (s[w]==FALSE)) { min=dist[w]; j=w; } } Dept of MCA,RVCE 40

return(j); } Enter the no. of vertices:6 Enter the cost matrix(row wise) -Enter 9999 for noedge or INFINITY 0 15 10 9999 45 9999 0 15 9999 20 20 9999 0 0 9999 9999 10 9999 0 35 9999 9999 9999 30 0 9999 9999 9999 4 9999 Enter the starting node:5 9999 9999 9999 9999 9999 0

Shortest path from starting node to Destination Node is as shown below Destination Node 1 2 3 4 6 | | | | | | Distance 75 40 55 30 9999

6. Find Minimum Cost Spanning Tree of a given undirected graph using Kruskals algorithm. Problem: To find the minimum cost spanning tree of a given undirected graph using kruskals method Mehtod: A spanning tree of a graph is any tree that includes every vertex in the graph. Little more formally, a spanning tree of a graph G is a sub-graph of G that is a tree and contains all the Dept of MCA,RVCE 41

vertices of G. An edge of a spanning tree is called a branch; an edge in the graph that is not in the spanning tree is called a chord. We construct spanning tree whenever we want to find a simple, cheap and yet efficient way to connect a set of terminals (computers, cites, factories, etc.). Spanning trees are important because of following reasons.

Spanning trees construct a sparse sub graph that tells a lot about the original graph. Spanning trees a very important in designing efficient routing algorithms. Some hard problems (e.g., Steiner tree problem and traveling salesman problem) can be solved approximately by using spanning trees. Spanning trees have wide applications in many areas, such as network design, etc.

Procedure Minimum Spanning Tree (MST) A minimum spanning tree of a weighted graph G is a spanning tree of G whose edges sum is minimum weight. In other words, a MST is a tree formed from a subset of the edges in a given undirected graph, with two properties: It spans the graph, i.e., it includes every vertex of the graph. It is a minimum, i.e., the total weight of all the edges is as low as possible. Source Code #include<stdio.h> typedef struct{ int node1; int node2; int wt; }edge; void sortedges(edge a[],int n){ int i,j; edge temp; for(i=0;i< n-1;++i) for(j=i+1;j< n;++j) Dept of MCA,RVCE 42

if(a[i].wt>a[j].wt){ temp=a[i]; a[i]=a[j]; a[j]=temp; } } int checkcycle(int p[],int i,int j){ int v1,v2; v1 = i; v2 = j; while(p[i]>-1) i = p[i]; while(p[j]>-1) j = p[j]; if(i!=j){ p[j]=i; printf("%d %d\n",v1,v2); return 1; } return 0; } int main() { edge e[100]; int parent[100]; int n,i,j,m,k = 1,cost = 0; printf("KRUSKAL's ALGORITHM\n"); printf("Enter number of nodes\n"); scanf("%d",&n); for(i=0;i< n;++i) Dept of MCA,RVCE 43

parent[i]=-1; printf("Enter number of edges\n"); scanf("%d",&m); for(i=0;i< m;++i){ printf("enter an edge and wt\n"); scanf("%d %d %d", &e[i].node1,&e[i].node2,&e[i].wt); } sortedges(e,m); printf("\n\nEdges of the tree\n"); i = 0; while(k< n){ if(checkcycle(parent,e[i].node1,e[i].node2)){ k++; cost=cost+e[i].wt; i++; } } printf("cost = %d",cost); return 0; } Enter the number of nodes 10 Enter the number of edges 10 Enter the edge list Enter the next edge(u,v) 1 2 Enter the cost Dept of MCA,RVCE 44

8 Enter the next edge(u,v) 9 9 Enter the cost 0 Enter the next edge(u,v) 7 7 Enter the cost 77 Enter the next edge(u,v) 8 9 Enter the cost 78 Enter the next edge(u,v) 8 9 Enter the cost 8 Enter the next edge(u,v) 9 9 Enter the cost 8 Enter the next edge(u,v) 8 9 Enter the cost Dept of MCA,RVCE 45

8 Enter the next edge(u,v) 89 88 Enter the cost 88 Enter the next edge(u,v) 8 89 Enter the cost 0 Enter the next edge(u,v) 89 88 Enter the cost 9 Output spanning tree donot exist 7a. Print all the nodes reachable from a given starting node in a digraph using BFS method. Problem: To find all the reachable nodes using Breadth First Search Method: The algorithm uses traversal techniques to reach the nodes Procedure: Algorithm BFS(G) // Implements a BFS traversal of a given graph // Input: Graph = (V,E)

Dept of MCA,RVCE

46

// output: Graph G with its vertices marked with consecutive integers in the order they have been visited by the BFS traversal mark each vertex in V with 0 as a mark of being unvisited Count <- 0 For each vertex v in V do If v is marked with 0 bfs(v) bfs(v) // Visits all the unvisited vertices connected to vertex v and assigns them the numbers in the order they are visited via global variable count count = count + 1 // mark v with count and initialize a queue with v while the queue is not empty do for each vertex w in v adjacent to the fronts vertex v do if w is marked with 0 count = count + 1 add w to the queue remove vertex v from the front of the queue First, each vertex is clearly marked at most once, added to the list at most once (since that happens only when it's marked), and therefore removed from the list at most once. Since the time to process a vertex is proportional to the length of its adjacency list, the total time for the whole algorithm is O(m). Usage: Use of breadth first search arises in certain pattern matching problems. Source Code #include<stdio.h> #define MAX 20 int cnt=1; void main() Dept of MCA,RVCE 47

{ int i,j,a[MAX][MAX],cov[MAX],q[MAX]; int n,strt; printf("Enter the total Number of Nodes:"); scanf("%d",&n); printf("Enter Matrix\n"); for(i=1;i<=n;i++) for(j=1;j<=n;j++) scanf("%d",&a[i][j]); printf("Entered Matrix\n"); for(i=1;i<=n;i++){ for(j=1;j<=n;j++) printf("%3d",a[i][j]); printf("\n"); } printf("Enter the start vertex\n"); scanf("%d",&strt); for(i=1;i<=MAX;i++) { q[i]=0; cov[i]=0; } cov[strt]=1; q[1]=strt; j=1; while(q[j]!=0) { cov[q[j]]=1; for(i=1;i<=n;i++) if((a[q[j]][i]==1) && !cov[i]) Dept of MCA,RVCE 48

{ q[++cnt]=i; cov[i]=1; } j++; } for(i=1;i<=cnt;i++) printf(" %3d->",q[i]); printf("\t\t %d",q[i]); } Enter the total Number of Nodes:10 Enter Matrix 0 1 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 Entered Matrix is 0 1 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 Dept of MCA,RVCE 49

0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 Enter the start vertex 1 4 7 9 8 4 7 9 8

vertex 0is not reachable vertex1is reachable vertex 2is not reachable vertex 3is not reachable vertex4is reachable vertex 5is not reachable vertex 6is not reachable vertex7is reachable vertex8is reachable vertex9is reachable

Dept of MCA,RVCE

50

7.b Check whether a given graph is connected or not using DFS method Problem : To check the connectivity of the graph using DFS method. Method: Depth first search is another way of traversing graphs, which is closely related to preorder traversal of a tree. Recall that preorder traversal simply visits each node before its children. It is most easy to program as a recursive routine: preorder(node v) { visit(v); for each child w of v preorder(w); } To turn this into a graph traversal algorithm, we basically replace "child" by "neighbor". But to prevent infinite loops, we only want to visit each vertex once. We can use marks to keep track of the vertices that have already been visited, and not visit them again. Also, we can use this search to build a spanning tree with certain useful properties. Procedure: dfs (vertex v) { visit(v); for each neighbor w of v if w is unvisited { dfs(w); add edge vw to tree T } } Source Code: #include <stdio.h> Dept of MCA,RVCE 51

int a[10][10]; void main() { int j,i; int n,s,cov[10]; printf("\n Enter total Number of Verticies \n"); scanf("%d",&n); printf("Enter Matrix for %d Verticies",n); for(i=1;i<=n;i++) for(j=1;j<=n;j++) scanf("%d",&a[i][j]); printf("\nEnter starting vertex\n"); scanf("%d",&s); for(i=1;i<=n;i++) cov[i]=0; dfs(cov,s,n); printf("The vertices reachable are\n"); for(i=1;i<=n;i++) { if(cov[i]) printf("%d\t",i); } return 0; } dfs(int cov[],int s,int n) { int i; cov[s]=1; Dept of MCA,RVCE 52

for(i=1;i<=n;i++) { if(!cov[i] && a[s][i]) { dfs(cov,i,n); } } } enter the number of nodes 10 enter the cost adajacency matrix 0110000000 0000100000 0000010000 0000001000 0000000100 0000000100 0000000110 0000000001 0000000000 0000000010 enter the source 1 node 0 is not reachable node 1 is reachable node 2 is not reachable node 3 is not reachable node 4 is reachable node 5 is not reachable node 6 is not reachable node 7 is reachable node 8 is reachable node 9 is reachable the graph is not connected

Dept of MCA,RVCE

53

8. Find a subset of a given set S = {s1,2,.,sn} of n positive integers whose sum is equal to a given positive integer d. for example, if S={1,2,5,6,8} and d = 9 there are two solution {1,2,6} and {1,8}. A suitable message is to be displayed if the given problem instance doesnt have solution. Problem: An instance of the Subset Sum problem is a pair (S, t), where S = {x1 , x2 , ..., xn } is a set of positive integers and t (the target) is a positive integer. The decision problem asks for a subset of S whose sum is as large as possible, but not larger than t. This problem is NP-complete. Method: The algorithm uses backtracking method to solve the problem. Procedure: void sumofsubsets(int s,int k, int r) { x[k]=1; if(s+w[k] == d) { flag =1; printf("\n subset %d", ++count); for(i=0;i<=k;i++) if(x[i]==1) printf("%d",w[i]); } else if(s+w[k] +w[k+1]<=d) sumofsubsets(s+w[k],k+1,r-w[k]); if((s+r-w[k] >=d) && (s+w[k+1]<=d)) { x[k]=0; sumofsubsets(s,k+1,r-w[k]); } } Source Code #include<stdio.h> int w[10],d,n,count=0,x[10],i,flag=0; void sumofsubsets(int s,int k, int r) Dept of MCA,RVCE 54

{ x[k]=1; if(s+w[k] == d) { flag =1; printf("\n subset %d", ++count); for(i=0;i<=k;i++) if(x[i]==1) printf("%d",w[i]); } else if(s+w[k] +w[k+1]<=d) sumofsubsets(s+w[k],k+1,r-w[k]); if((s+r-w[k] >=d) && (s+w[k+1]<=d)) { x[k]=0; sumofsubsets(s,k+1,r-w[k]); } } int main() { int s,r=0,k; printf("Enter the number of elements\n"); scanf("%d",&n); printf("Enter the elements in ascending order\n"); for(i=0;i<n;i++) scanf("%d",&w[i]); printf("Enter the sum\n"); scanf("%d",&d); for(i=0;i<n;i++) x[i]=0; for(i=0;i<n;i++) r+=w[i]; sumofsubsets(0,0,r); if(flag==0) printf("\n solution not possible\n"); } Enter the number of elements 6 Enter the elements in ascending order 3 4 5 67 8 Enter the sum 13 subset 1 3,4,6 Dept of MCA,RVCE 55

subset 2 subset 3

5,8 6,7

9. Implement any scheme to find the optimal solution for the Traveling Salesperson problem and then solve the same problem instance using any approximation algorithm and determine the error in the approximation. Problem: To find an optimal solution for the travelling salesman problem and solve the same problem instance using any approximation algorithm and determine the error in the approximation. Method: The travelling salesman problem can be solved using greedymethod, dynamic programming method, heuristic method etc. The approximation algorithms which can be used for travelling salesman problem includes DFS,BFS,2-opt algorithm, v-opt algorithm, LKH algorithm etc. In this problem the DFS algorithm is used and the cost is found. The same source code of DFS can be used along with the following modification : Proceudre for finding cost using approximation is printf("Enter the cost matrix of the vertices\n"); for(i=1;i<=n;i++) { scanf ("%d",&cost[i]); sum = sum + cost[i]; } printf("the tour cost is %d",sum); The DFS method also produces the same output. Therefore the error value is NIL. Source Code /* C program to demonstrate travelling salesperson problem. */

Dept of MCA,RVCE

56

#include <stdio.h> #define MAX 100 #define INFINITY 999 int tsp_dp (int c[][MAX], int tour[], int start, int n); int main() { int n; /* Number of cities. */ int i, j; /* Loop counters. */ int c[MAX][MAX]; /* Cost matrix. */ int tour[MAX]; /* Tour matrix. */ int cost; /* Least cost. */ printf ("This program demonstrates the TSP problem."); printf ("\nHow many cities to traverse? "); scanf ("%d", &n); printf ("Enter the cost matrix: (999: no connection)\n"); for (i=0; i<n; i++) for (j=0; j<n; j++) scanf ("%d", &c[i][j]); for (i=0; i<n; i++) tour[i] = i; cost = tsp_dp (c, tour, 0, n); rintf ("Minimum cost: %d.\nTour: ", cost); for (i=0; i<n; i++) Dept of MCA,RVCE 57

printf ("%d ", tour[i]+1); printf ("1\n"); } int tsp_dp (int c[][MAX], int tour[], int start, int n) { int i, j, k; /* Loop counters. */ int temp[MAX]; /* Temporary during calculations. */ int mintour[MAX]; /* Minimal tour array. */ int mincost; /* Minimal cost. */ int ccost; /* Current cost. */ /* End of recursion condition. */ if (start == n - 2) return c[tour[n-2]][tour[n-1]] + c[tour[n-1]][0]; /* Compute the tour starting from the current city. */ mincost = INFINITY; for (i = start+1; i<n; i++) { for (j=0; j<n; j++) temp[j] = tour[j]; /* Adjust positions. */ temp[start+1] = tour[i]; temp[i] = tour[start+1]; /* Found a better cycle? (Recurrence derivable.) */

Dept of MCA,RVCE

58

if (c[tour[start]][tour[i]] + (ccost = tsp_dp (c, temp, start+1, n)) < mincost) { mincost = c[tour[start]][tour[i]] + ccost; for (k=0; k<n; k++) mintour[k] = temp[k]; } } for (i=0; i<n; i++) tour[i] = mintour[i]; return mincost; } Travelling Salesman Problem How many cities to traverse? 3 Enter the cost matrix: (999: no connection) 999 200 400 200 999 200 400 200 999 Minimum cost: 800. Tour: 1 2 3 1 Error approximation =0. 10. Find Minimum Cost Spanning Tree of a given undirected graph using Prims algorithm. Problem To find the minimum cost spanning tree of the undirected graph using prim's method. Method: Prims algorithm

Dept of MCA,RVCE

59

It starts from an arbitrary vertex (root) and at each stage, add a new branch (edge) to the tree already constructed; the algorithm halts when all the vertices in the graph have been reached. This strategy is greedy in the sense that at each step the partial spanning tree is augmented with an edge that is the smallest among all possible adjacent edges. Analysis The algorithm spends most of its time in finding the smallest edge. So, time of the algorithm Basically depends on how we search this edge. Straightforward method Just find the smallest edge by searching the adjacency list of the vertices in V. In this case, each iteration costs O(m) time, yielding a total running time of O(mn). Now we describe the Prim's algorithm when the graph G =(V, E) is represented as an adjacency matrix. Instead of heap structure, we use an array to store the key of each node Procedure: A V[g] // Array For each vertex uQ do key [u] key [r] 0 [r] NIL while Array A empty do scan over A find the node u with smallest key, and remove it from array A for each vertex vAdj[u] if v A and w[u, v] < key[v] then [v] u key[v] w[u, v] let T be a single vertex x while (T has fewer than n vertices) { find the smallest edge connecting T to G-T add it to T Dept of MCA,RVCE 60

} Source Code: #include<stdio.h> #include<stdlib.h> #define MAX 6 #define INFINITY 999 void prim(int [][MAX],int); int edge[MAX][2]; void main() { int cost[MAX][MAX], n, mincost=0, i,j; printf("\n Enter the no of vertices:\n"); scanf("%d",&n); printf("\nEnter the Cost Adjacency Matrix for %d Verticies \n",n); printf("(enter 9999 to indicate no edge)\n"); for(i=1;i<=n;i++) for(j=1;j<=n;j++) scanf("%d",&cost[i][j]); printf("\nEntered Cost Adjacency Matrix as followes \n",n); for(i=1;i<=n;i++){ for(j=1;j<=n;j++) printf("%5d",cost[i][j]); printf("\n"); } prim(cost,n); for(i=1;i<=n-1;i++) mincost+=cost[edge[i][1]][edge[i][2]]; printf("\nThe solution to MWST = %d\n",mincost); if(mincost>=1000) { Dept of MCA,RVCE 61

printf("There is no Minimum Spanning Tree\n"); exit(1); } printf("\n Edges of the Minimum spanning tree\n"); for(i=1;i<=n;i++) printf("<%2d,%2d>",edge[i][1],edge[i][2]); } void prim(int cost [][MAX],int n) { int closest[MAX]; int lowcost[MAX],min; int i,j,k; for(i=2;i<=n;i++) { lowcost[i]=cost[1][i]; closest[i]=1; } for(i=2;i<=n;i++) { min=lowcost[2]; k=2; for(j=3;j<=n;j++) if(lowcost[j]<min) { min=lowcost[j]; k=j; } edge[i-1][1]=closest[k]; edge[i-1][2]=k; lowcost[k]=INFINITY; for(j=2;j<=n;j++) if(cost[k][j]<lowcost[j]) if(lowcost[j]<INFINITY) { lowcost[j]=cost[k][j]; closest[j]=k; } } } Prims Algorithm Enter the no of vertices: 3 Dept of MCA,RVCE 62

Enter the Cost Adjacency Matrix for 3 Verticies (enter 9999 to indicate no edge) 9999 45 50 45 999 60 50 60 999 Entered Cost Adjacency Matrix as follows 9999 45 50 45 999 60 50 60 999 The solution to MWST = 95 11. Implement Floyds algorithm for the All-pairs-Shortest-Paths Problem. Parallelize this algorithm, implement using OpenMP and determine the speed up achieved. Problem: To find the shortest path for all the pairs of the graph using floyds algorithm and implement openMP method to parallelize the algorithm. Method: OpenMP Methods: 1. #include<omp.h> : It is the header file which should be used to implement the functions using open MP 2.#pragma omp parallel private(var1, var2) shared(var3) { Parallel section executed by all threads . . . All threads join master thread and disband } This section is used to parallelize all the sections using threds. Dept of MCA,RVCE 63

3.

#pragma omp for nowait : Helps to parallely run the for loops

Execution : To execute programs using open MP concepts the command is gcc -fopenmp filename.c Procedure: allpairs(cost,a,n); printf("\n The shortest path matrix obtained is as followes \n"); for(i=1;i<=n;i++) { for(j=1;j<=n;j++) printf("%3d",a[i][j]); printf("\n"); } void allpairs(int c[][MAX],int a[][MAX],int n) { int s,i,j,k; for(i=1;i<=n;i++) for(j=1;j<=n;j++) if (i==j) a[i][j]=0; else a[i][j]=c[i][j]; for(k=1;k<=n;k++) for(i=1;i<=n;i++) for(j=1;j<=n;j++) Dept of MCA,RVCE 64

a[i][j]=min(a[i][j],a[i][k]+a[k][j]); } Source Code: #include<stdio.h> #include<sys/time.h> #define TRUE 1 #define MAX 10 #define INFINITY 999 struct Timer { int time; }mytimer; void allpairs(int [][MAX],int [][MAX],int); int min(int,int); void main() { int cost[MAX][MAX]; int a[MAX][MAX]; int n; int i,j; struct timeval st,en; printf("Enter the no of vertices:"); scanf("%d",&n); Dept of MCA,RVCE 65

printf("Vertices Considered : %d ",n); printf("\nEnter the cost adjacency matrix\n and 999 for no cost\n "); for(i=1;i<=n;i++) for(j=1;j<=n;j++) scanf("%d",&cost[i][j]); printf("\nEntered cost adjacency Matrix as follows \n"); for(i=1;i<=n;i++) { for(j=1;j<=n;j++) printf(" %3d ",cost[i][j]); printf("\n"); } gettimeofday(&st,0); allpairs(cost,a,n); gettimeofday(&en,0); mytimer.time=(en.tv_usec-st.tv_usec);

printf("the time taken is %d micro seconds",mytimer.time);

printf("\n The shortest path matrix obtained is as followes \n"); for(i=1;i<=n;i++) { for(j=1;j<=n;j++) printf("%3d",a[i][j]); Dept of MCA,RVCE 66

printf("\n"); } } void allpairs(int c[][MAX],int a[][MAX],int n) { int s,i,j,k; { #pragma omp parallel shared(n,a,c,nthreads) private(i,tid) { tid = omp_get_thread_num(); /* Only master thread does this */ if (tid == 0) { nthreads = omp_get_num_threads(); printf("Number of threads = %d\n", nthreads); } #pragma omp for nowait for(i=1;i<=n;i++) for(j=1;j<=n;j++) if (i==j) a[i][j]=0; else a[i][j]=c[i][j]; Dept of MCA,RVCE 67

for(k=1;k<=n;k++) for(i=1;i<=n;i++) for(j=1;j<=n;j++) a[i][j]=min(a[i][j],a[i][k]+a[k][j]); } exit(0); }} int min(int a,int b) { return(a<b)?a:b; } Enter the no of vertices:4 Vertices Considered : 4 Enter the cost adjacency matrix Enter 999 for no cost 999 999 3 999 2 999 999 999 999 7 999 1 6 999 999 999 Entered cost adjacency Matrix as follows 999 999 3 999 2 999 999 999 999 7 999 1 Dept of MCA,RVCE 68

6 999 999 999 The time taken is 4 micro seconds The shortest Path obtained is : 0 10 3 4 2056 7701 6 16 9 0 No.of threads=4 12.Implement N Queens problem using Back Tracking Problem The n-queens problem is to place n queens on an n-by-n chessboard so that no two queens attach each other by being in the same row or in the same column or on the same diagonal.s Method: The method applied to solve the problem is Backtracking. The principal idea is to construct solutions one component at a time and evaluate such partially constructed candidates. If a partially constructed solution can be developed further without violating the problems constraints, it is done by taking trhe first remaining legitimate option for the next component. If there is not legitimate option for the next component, no alternatives for any remaining component need to be considered. In this case, the algorithm backtracks to replace the last component fo the partially constructed solution with its next option. Procedure: void nqueens(int x[],int n) { int k; x[0]=-1; k=0; while(k>=0) { x[k]=x[k]+1; while(x[k]<n && !place(x,k)) Dept of MCA,RVCE 69

x[k]=x[k]+1; if(x[k]<n) if(k==n-1) { display(x,n); return; } Source Code: #include<stdio.h> #include<math.h> #define MAX 20 #define TRUE 1 #define FALSE 0 void display(int [],int); void nqueens(int [],int); int place(int [],int); void main() { int x[MAX]; int i,j,n; printf("Enter the number of queens:"); scanf("%d",&n); if(n>=3) { printf("The solution to %d Queens problem is:\n",n); nqueens(x,n); } else printf("Number of queens should be greater than 3\n"); } void nqueens(int x[],int n) { int k; x[0]=-1; k=0; while(k>=0) { Dept of MCA,RVCE 70

x[k]=x[k]+1; while(x[k]<n && !place(x,k)) x[k]=x[k]+1; if(x[k]<n) if(k==n-1) { display(x,n); return; } else { k++; x[k]=-1; } else k--; } } int place(int x[],int k) { int i; for(i=0;i<k;i++) if(x[i]==x[k] || (abs(x[i]-x[k])==abs(i-k))) return (FALSE); return (TRUE); } void display(int x[],int n) { int s[MAX][MAX]; int i,j; for(i=0;i<n;i++) for(j=0;j<n;j++) s[i][j]=0; for(i=0;i<n;i++) s[i][x[i]]=TRUE; for(i=0;i<n;i++) { for(j=0;j<n;j++) printf(" %d ",s[i][j]); printf("\n"); } } Dept of MCA,RVCE 71

Enter the number of queens:4 The solution to 4 Queens problem is: 0 1 0 0 0 0 0 1 1 0 0 0 0 0 1 0

Dept of MCA,RVCE

72

EXTRA QUESTIONS
1.

Write a program to implement linear search using c++

2. Implement binary search and analyse the efficiency of the algorithm 3. Implement strassen matrix multiplication using divide and conquer method
4.

Implement graph coloring algorithm using backtracking method

5. Implement kanpsack problem using backtracking method in c++. 6. Write a program to sort a given set of numbers using heap sort in c++. The numbers should be read from a file. 7. Write a program to implement horsepool algorithm in c++ 8. Implement binomial co-efficient using c++ 9. Write a program to implement linear search and find the speed of the algorithm 10. Write a program to implement dijkstras algorithm

Dept of MCA,RVCE

73

VIVA QUESTIONS 1. Define an algorithm 2. Define recursion 3. Mention the different types of order of growth? 4. Define notation 5. Define time complexity 6. Define space complexity
7.

What are the factors on which the time efficiency of an algorithm depend

8. Explain how do we implement time in c and c++. 9. What are the different methodologies applied in finding the efficiency of an algorithm 10. Explain Quick sort method 11. What is open MP 12. What is the header file used to work on open MP 13. What are the various steps in which a program can be parallelized. 14. Differentiate omp for nowait and section nowait 15. What is order of growth of merge sort 16. What do you mean by topological ordering 17. What do you mean by mean by All-pairs shortest path problem? 18. What do you mean by dynamic programming 19. What is the difference between dynamic programming and divide and conquer 20. What is knapsack problem? 21. What is Dijkstras algorithm? 22. Whether Dijkstras can be implemented for directed graph 23. What do you mean by Spanning tree? 24. What is order of growth of quick sort 25. What is the difference between Prims and Kruskal algorithm 26. Which is the best sorting technique and why? 27. What is the difference between directed and undirected graph 28. What is the difference between Floyds and Dijkstras algorithm 29. What do you mean by DFS 30. What do you mean by BFS Dept of MCA,RVCE 74

31. What do you mean by transitive closure of a given graph? 32. How do you get the transitive closure of a given graph using Warshalls algorithm 33. What do you mean by queens problem? 34. What is the difference between branch and bound and backtracking? 35. What is the difference between NP and NP-hard problems 36. What is the difference between p and NP problems 37. What do you mean by subset problem? 38. What do you mean by graph problems 39. What do you mean by exhaustive search problem 40. Write down the order of growth depending upon their efficiencies 41. What is travelling salesman problem. 42. What are the various methods that can be implemented to solve travelling salesman problem 43. What is approximation algorithm 44. Define topological sorting. 45. What are the applications of travelling salesman problem 46. Where do we apply topological sorting. 47. Define horsepool problem 48. What is an approximate solution 49. How do we find the error in approximation 50. Give the difference between kruskals method and prims method.

Dept of MCA,RVCE

75

R.V.COLLEGE OF ENGINEERING DEPARTMENTOF M.C.A 10MCA 48 ALGORTIHMS LABORATORY Lab Cycle 1: Sort a given set of elements using the Quick sort method and determine the time required to sort the elements. Repeat the experiment for different values of n, the number of elements in the list to be sorted and plot a graph of the time taken versus n. The elements can be read from a file or can be generated using the random number generator. Lab Cycle 2: Using OpenMP, implement a parallelized Merge Sort algorithm to sort a given set of elements and determine the time required to sort the elements. Repeat the experiment for different values of n, the number of elements in the list to be sorted and plot a graph of the time taken versus n. The elements can be read from a file or can be generated using the random number generator. Lab Cycle 3 3a. Obtain the Topological ordering of vertices in a given digraph. 3b. Compute the transitive closure of a given directed graph using Warshall's algorithm Lab Cycle 4: 4. Implement 0/1 Knapsack problem using Dynamic Programming.

5 . From a given vertex in a weighted connected graph, find shortest paths to other vertices using Dijkstra's algorithm Lab Cycle 5: 6. Find Minimum Cost Spanning Tree of a given undirected graph using Kruskal's algorithm. Lab Cycle 6: 7. a. Print all the nodes reachable from a given starting node in a digraph using BFS method. b. Check whether a given graph is connected or not using DFS method. Dept of MCA,RVCE 76

Lab Cycle 7: 8. Find a subset of a given set S = {sl,s2,.....,sn} of n positive integers whose sum is equal to a given positive integer d. For example, if S= {1, 2, 5, 6, 8} and d = 9 there are two solutions{1,2,6}and{1,8}.A suitable message is to be displayed if the given problem instance doesn't have a solution. Lab Cycle 8: 9. Implement any scheme to find the optimal solution for the Traveling Salesperson problem and then solve the same problem instance using any approximation algorithm and determine the error in the approximation. 10. Find Minimum Cost Spanning Tree of a given undirected graph using Prims algorithm. Lab Cycle 9: 11. Implement All-Pairs Shortest Paths Problem using Floyd's algorithm. Parallelize this algorithm, implement it using OpenMP and determine the speed-up achieved. 12. Implement N Queen's problem using Back Tracking. Lab Cycle 10: Backlogs if any.

Instructions:
Students are required to write the aim, program in c/c++ and three inputs in the data sheet. They are also required to bring graph sheets whenever necessary.

Procedure for writing record: Left Hand Side:


1. A short description about the program 2. Pseudocode of the program 3. Input and Output.

Right Hand Side:


1. Program

Evaluation in the Lab: 7 marks Execution and 3 marks for Viva

Dept of MCA,RVCE

77

Potrebbero piacerti anche