Hax4Us

Dp1

Jun 19th, 2019
161
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.62 KB | None | 0 0
  1. /* Example of Dynamic programmig
  2.  using Tabular Method */
  3.  
  4. #include <stdio.h>
  5. #define MAX(a,b) ((a>b)?a:b)
  6. #define UPPERSEQ 1
  7. #define LOWERSEQ 2
  8.  
  9. int get_subseq(int a,int b,int i) {
  10.         if(i%2==0) {
  11.                 if(a==MAX(a,b))
  12.                         return UPPERSEQ;
  13.                 else
  14.                         return LOWERSEQ;
  15.         }
  16.         else {
  17.                 if(a==MAX(a,b))
  18.                         return LOWERSEQ;
  19.  
  20.                 else
  21.                         return UPPERSEQ;
  22.         }
  23. }
  24.  
  25. int main(void) {
  26.         const int n = 6;
  27.         int i=2;
  28.         int a[n] = { 1,3,2,6,4,2};
  29.         int sum[n]; // our table that will keep track of old sums
  30.         sum[0]=a[0];
  31.         sum[1]=a[1];
  32.         while(i<n){
  33.                 sum[i]=MAX((sum[i-2] + a[i]),sum[i-1]);i++;
  34.         }
  35.         printf("max : %d\n",sum[i-1]);
  36.         // its not part of my example but just for fun we ill find the numbers
  37.         //when sums will be equal
  38.         if(sum[i-1] == sum[i-2]){                                                          
  39.                 printf("Elements can not be decided because there are two same max sums exist");                                                                        
  40.                 return 1;
  41.         }
  42.         printf("elements : ");
  43.         for(int j=0;j<n;j++) {                                                                   if(get_subseq((sum[i-3]+a[i-1]),sum[i-2],i-1) == UPPERSEQ) {
  44.                         printf("%d\t",a[j]);j++;
  45.                 }
  46.                 else
  47.                         printf("%d\t",a[++j]);
  48.         }
  49.         return 0;
  50. }
Add Comment
Please, Sign In to add comment