Showing posts with label Dynamic programming. Show all posts
Showing posts with label Dynamic programming. Show all posts

Sunday, August 2, 2015

Pizza Stack

Kamaldeep is good at making pizzas. Generally he gets requests to serve N pizzas at once. He serves them in the form of a stack. A pizza should be treated as a circular disk with some radius.
Kamaldeep needs to take care that when he places a pizza on the top of the stack the radius of the pizza should not exceed the radius of the largest pizza in the stack by more than 1. Additionally all radii should be positive integers, and the bottom most pizza should have its radius as 1. Kamaldeep is week in maths :P, so he wants you to find out in how many ways can he create a stack containing N pizzas.
Input
First line of the input contains T (T <= 1000) denoting the number of test cases.
T lines follow each containing a single integer N (1 <= N <= 1000) denoting the size of the required stack.
Output
For each case the output should be a single integer representing the number of ways a stack of size N can be created. As
the answer can be large print it modulo 1000000007.



ANS------->

dp[i][j] -> stack size of i with j different value .


dp[i][j] = j*dp[i-1][j] + dp[i-1][j-1];


  1. #include <iostream>
  2. using namespace std;
  3.  
  4. int main()
  5. {
  6. int t ;
  7. cin >> t;
  8. long long mo = 1000000007;
  9.  
  10. long long dp[1002][1002];
  11. long long top[1002];
  12. for(int i=0 ; i < 1002 ; i++)
  13. for(int j=0 ; j < 1002 ; j++)
  14. dp[i][j]=0;
  15.  
  16. dp[1][1]=1 ;
  17. top[1]=1;
  18. for(int i=2 ; i < 1002 ; i++){
  19. long long temp = 0 ;
  20. for(int j=1; j<=i; j++){
  21. dp[i][j]=j*dp[i-1][j]%mo + dp[i-1][j-1]%mo;
  22. temp=(temp+dp[i][j])%mo;
  23. }
  24. top[i]=temp;
  25. }
  26. while(t--){
  27. int val ;
  28. cin >> val ;
  29. cout << top[val] << endl ;
  30. }
  31.  
  32. return 0;
  33. }







Saturday, April 19, 2014

The Indian Job

It is the Indian version of the famous heist “The Italian Job”. N robbers have already broken into the National Museum and are just about to get inside the main vault which is full of jewels. They were lucky that just as they broke into the museum, the guard was leaving the museum for exactly G minutes. But there are other problems too. The main vault has heat sensors that if at any moment of time there are more than two people present in the vault, the alarm goes off.
To collect the jewels, the ith robber needs to be inside the vault for exactly A[i]minutes, 0 <= i < N, in one continuous stretch. As guard will return after G minutes, they have to finish their tasks within G minutes. The robbers want to know if there exists any arrangement such that demands of each robber is satisfied and also they are not caught?
Gotchas
If a robber goes inside the vault at a time “X” and at the same time another robber comes out, it’s equivalent to saying they were never in the vault at the same time.
Similarly, when the guard gets inside vault at time G and a robber comes out exactly at time G, the guard will not be able see the robber.
Input Format
The first line contains an integer T denoting the number of testcases. T testcases follow. Each testcase consists of two lines. First line contains two space separated integers denoting N and G denoting the number of thieves and duration for which guard leaves the museum.
The next line contains N space separated numbers where the ith integer, A[i] represents the time the ith robber needs to be in the vault.
Output Format
For each testcase print YES if there exists such an arrangement or NO otherwise in a newline.
Constraints
1 <= T <= 20
1 <= N <= 100
0 <= G <= 1000000 (106)
0 <= A[i] <= 100
Sample Input
2
3 4
2 4 2
3 2
2 4 2
Sample Output
YES
NO
Explanation
Test case #00: In first testcase, one possible arrangement is:
at t=0, robber1 goes inside and comes out at t=2
at t=0, robber2 goes inside and comes out at t=4
at t=2, robber3 goes inside and comes out at t=4
Test case #01: No possible arrangement is possible in second testcase.
solution--> it a partition problem . we need to max value of sub array minimum then G(guard time).
code-->

#include<iostream>
using namespace std ;

void calculate(int arr[], int g , int n)
{
    int sum = 0 , max;
    int i, j;
   
    // Caculcate sun of all elements
    for (i = 0; i < n; i++)
      sum += arr[i];
     
   
    bool part[g+1][n+1];
  
    // initialize top row as true
    for (i = 0; i <= n; i++)
      part[0][i] = true;
       
    // initialize leftmost column, except part[0][0], as 0
    for (i = 1; i <= g; i++)
      part[i][0] = false;     
      
     // Fill the partition table in botton up manner 
     for (i = 1; i <= g; i++)  
     {
       for (j = 1; j <= n; j++)  
       {
         part[i][j] = part[i][j-1];
         if (i >= arr[j-1])
           part[i][j] = part[i][j] || part[i - arr[j-1]][j-1];
       }        
     }
    
    for(i=g;i>=0;i--){
        
        if(part[i][n]==true){
            max=i ;
            break ;
        }
    }    
    if(2*max>=sum)
        cout << "YES" << endl ;
    else
        cout << "NO"  << endl ;   
}   

  
int main(){
  int t ;
   cin >> t ;
  while(t--){
    int  n , g , i;
    cin >> n ;
    cin >> g ;
     int arr[n];
     for(i=0;i<n;i++)
      cin >> arr[i];
    calculate(arr,g,n);
  } 
}

Sunday, April 13, 2014

Find Largest Sub-Matrix With All 1s (Not Necessarily Square)

In this post, we will discuss how to find largest all 1s sub-matrix in a binary matrix. The resultant sub-matrix is not necessarily a square sub-matrix.

Example:
1 1 0 0 1 0
0 1 1 1 1 1
1 1 1 1 1 0
0 0 1 1 0 0
Largest all 1s sub-matrix is from (1,1) to (2,4).
1 1 1 1
1 1 1 1
Algorithm: If we draw a histogram of all 1’s cells in above rows (until we find a 0) for a particular row, then maximum all 1s sub-matrix ending in that row will the equal to maximum area rectangle in that histogram. Below is the example for 3rd row in above discussed matrix:
If we calculate this area for all the rows, maximum area will be our answer. We can extend our solution very easily to find start and end co-ordinates.

For above purpose, we need to generate an auxiliary matrix S[][] where each element represents the number of 1s above and including it, up until the first 0. S[][] for above matrix will be as shown below:
1 1 0 0 1 0
0 2 1 1 2 1
1 3 2 2 3 0
0 0 3 3 0 0
Now we can simple call our maximum rectangle in histogram on every row in S[][] and update the maximum area every time.

Also we don’t need any extra space for saving S. We can update original matrix (A) to S and after calculation, we can convert S back to A.

Maximum Area Rectangle In Histogram

Question: Find the maximum rectangle (in terms of area) under a histogram in linear time. I mean the area of largest rectangle that fits entirely in the Histogram.

(Please refer figures before code section for clarity. If I include bar i completely, those figure will tell how much maximum area rectangle I can get.)


Answer: A straightforward answer is to go for each bar in the histogram and find the maximum possible area in histogram for it. Finally find the maximum of these values. This will require O(n^2) time but this will be huge if we have a big histogram with thousands of bars. So we need to have an algorithm of O(n*logn) or O(n).

Lets see if we can find one such solution:

There are a few invariants, we can use for this problem:
  1. If we include bar i, maximum possible height of rectangle including that bar will be h(i), height of that bar.
  2. If we include bar i, maximum possible width of rectangle including that bar will be L+R+1, where:
  • L is number of adjacent bars to the left of ith bar and height greater than or equal to h(i).
  • R is number of adjacent bars to the right of ith bar and height greater than or equal to h(i).
For the figure in question, if we include bar i, we will have max area as given in below pictures.

Now our task remains as follows:
1) Get Li
2) Get Ri
3) Get area of rectangle for bar i: A(i) = h(i) * (Li+Ri+1)
4) Find max value of A(i)

How to get Li:
Li is the number of adjacent bars to the left of ith bar and height greater than h(i). How can we calculate this?

One solution is to for each I, traverse through i to 0 until you get a bar of height less than h(i). This will be an O(n^2) solution to find all the Li.

But we can have a better solution, which works in less than O(n^2). Lets see an example; in example figure, what is the farthest bar greater than or equal to h(9) (h(9) =2 in our case). Here we are seeing that 4th bar is just short of h(9), so we can move left till 5th bar. So we don’t need to compare with 3rd, 2nd and 1st bar in this case.

Similarly, if I want to put a new value in the stack, which points we should compare h(i) to find L? : 10th, 9th and 4 th. Coz if we can include 9th bar, we can certainly include 8th, 7th, 6th and 5th bar as they have height greater than h(9).

Now if I use a stack and put only those bars in stack, which are possible candidates. And pop those values until I get a bar with height less than h(i). Finally Li = (i – TOP-of-stack).


Complexity: In first impression, this solution seems to be having O(n^2) complexity. But if we look carefully, we can just put at the max N bars in stack at any point in time. And we are not pushing any bar twice. So we can pop at most N bar while calculating Li for complete histogram. So work time complexity is O(n+n) = O(2n) = O(n)

How to get Ri:
Similarly as we found Li. Just start from the end in place of beginning.


code ---->


#include<iostream>
#include<stack>

using namespace std ;

void findrect(int arr[],int len){

int area[len] ,i , maximum ,t ;
stack<int> s;

for(i=0;i<len;i++)
    area[i]=1;

// calculating Li

for(i=0;i<len;i++){

    while(!s.empty()){
         if(arr[s.top()]>=arr[i])
            s.pop();
         else
            break ;
    }

    if(s.empty())
        t=-1;
    else
        t=s.top();

    area[i]+=i-t-1;
   s.push(i);
}

// clearing the stack for calculating Ri;

while(!s.empty())
    s.pop();

for(i=len-1 ; i >=0 ;i--){

   while(!s.empty()){
    if(arr[s.top()] >=arr[i])
     s.pop();
     else
        break;
   }

   if(s.empty())
    t=len;
    else
     t=s.top();

area[i]+=t-i-1;
    s.push(i);
}
maximum=arr[0]*area[0];

for(i=1;i<len;i++)
    if(maximum < arr[i]*area[i])
      maximum=arr[i]*area[i];

cout << " max area in histogram is " << maximum  << endl ;
}

int main(){
int arr[]={9,6,2,1,3,5,4,8,3,7} ;
int y = sizeof(arr)/sizeof(arr[0]);
findrect(arr,y);
}

Thursday, April 10, 2014

Finding Maximum Sum in Triangle ( excellent Dynamic programming )

By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23.

3
7 4
2 4 6
8 5 9 3

That is, 3 + 7 + 4 + 9 = 23.


The problem required us to determine the maximum sum for any given triangle. Also an interesting thing is mentioned about the problem, in case you were considering a brute force method of checking every path:

It is not possible to try every route to solve this problem (where the base of the triangle has 100 numbers), as there are 2^(99) altogether! If you could check one trillion (10^(12)) routes every second it would take over twenty billion years to check them all. There is an efficient algorithm to solve it.

This problem was not as tricky as they tried to sound it. The solution is quite easy to see. I’ll run you through the idea as it formed in my mind. I used the top-to-bottom approach for forming the idea and coming up with the solution, and then implemented the solution in bottom-to-top sweep. I hope you have realized that a greedy solution will not work here.

Consider the triangle given above. I’ll work out the maximum path for it from top to bottom. We start with 3. We may choose either 7 or 4. To help make this choice, consider the two triangles with apex 7 and the other with 4. So we have two smaller triangles of height 3 each. Say the maximum length for the triangle with apex 7 is x and with apex 4 is y. If x > y, we choose 7 as the next on the path, else 4.


Thus, at every step we form two triangle of height 1 smaller, and choose the apex which has the larger sum. Implemented as it is will give us the recursive solution.

input triangle -->

int arr[][]= {{3},
         {7,4},
         {2,4,6},
         {8,5,9,3}};

we create a array according to given  given triangle . and fill the value according .

int array[][]={{0},
           {0,0},
           {0,0,0},
           {0,0,0,0}};

if(j==0)
 array[i][j]=array[i-1][j]+arr[i][j] ;
else
     if(j==array[i].length-1)
         array[i][j] = array[i-1][j-1]+arr[i][j] ;
      else
         array[i][j] = max(array[i-1][j-1],array[i-1][j])+arr[i][j] ;


after this we find the maximum value in the last row . and that is the answer . :D

code ---->

class TriangalSum{

static int max(int a,int b){
return a>b?a:b ;
}

static void maxSum(int arr[][]){

  int max ;
  int array[][]=new int[arr.length][];

for(int i=0;i<arr.length ;i++)
    array[i]= new int[arr[i].length];

  array[0][0]=arr[0][0];

for(int i=1;i<array.length ;i++){
for(int j=0;j<array[i].length ;j++){
 
if(j==0)
array[i][j]=array[i-1][j] + arr[i][j];
else{
  if(j==array[i].length - 1)
     array[i][j]=array[i-1][j-1] + arr[i][j];
 else
    array[i][j] = max(array[i-1][j],array[i-1][j-1]) +arr[i][j] ;

  }
   }
}
max=array[array.length-1][0];

for(int i=1;i<array[array.length-1].length ;i++){
      if(array[array.length-1][i] > max)
  max  = array[array.length-1][i];
}

System.out.println("max sum is =" + max);
  }

public static void main(String s[]){
 
int arr[][]= {{3},
             {7,4},
 {2,4,6},
 {8,5,9,3}};
      maxSum(arr);    
}
}

        

Tuesday, April 8, 2014

Calculating Large Factorial

Factorial of a non-negative number n is denoted by n! and it is the product of all positive integers less than or equal to n. Hence factorial of 5 is:

1*2*3*4*5=120.




//Factorial.java
import java.util.Scanner;

/**
 *
 * @author Vijay Apurva
 */
public class Factorial {
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter the number:");
        int num=sc.nextInt();
        int fact=1;
        for (int i = 1; i <=num; i++) {
            fact*=i;
        }
        System.out.println("Factorial of "+num+" is : "+fact);
    }//main(-)
    
}//Factorial

The output of the program is as below:

Enter the number:
50
Factorial of 50 is : 0

When we change the data type of fact to long to increase size and run the same program we get the output as shown below:

Enter the number:
50
Factorial of 50 is : -3258495067890909184
No primitive data type of any language can be used to calculate large factorial. So how can we get the factorial of 50 or other numbers perfectly.?

In JAVA, we have BigInteger class in java.math package which can be used to store very large number and we will be using this class to calculate factorial of such numbers. So here goes a java program to calculate factorial of 50 or 100 or other numbers:



//FactorialDemo.java
import java.math.BigInteger;
import java.util.Scanner;

/**
 *
 * @author Vijay apurva
 */
class Factorial {

    int num;
    BigInteger bi = new BigInteger("1");

    public void read() {
        System.out.println("Enter a number:");
        Scanner sc = new Scanner(System.in);
        num = sc.nextInt();
    }//read()

    public void process() {
        if (num < 0) {
            System.out.println("Invalid number!");
            System.exit(1);
        }
        for (int i = 1; i <= num; i++) {
            bi = bi.multiply(BigInteger.valueOf(i));
        }
    }//process()

    public void display() {
        System.out.println("Factorial of " + num + " is : " + bi);
    }//display()
}//Factorial

public class FactorialDemo {

    public static void main(String[] args) {
        Factorial f=new Factorial();
        f.read();
        f.process();
        f.display();
    }//main(-)
}//FactorialDemo



he output of this program with 50 as input is as:

Enter a number:
50
Factorial of 50 is : 608281864034267560872252163321295376887552831379210240000000000

Can Also calculate  1,00,000 !  :D  :D