Thursday, 27 July 2017

SPOJ : MARBLES Solution

Question MARBLES - Marbles
Explaination....
Fill n spaces , with k colors.
First select k spaces with k-different color. 
Now we are left with n-k spaces ,which can be filled with any of the k colors. Now to fill m-spaces by r-color with each r is infinte amount,we do this..

Using a method that's often called "stars and bars":
We draw n
stars in a row to represent the cakes, and k1 bars to divide them up. All of the stars to the left of the first bar are cakes of the first type; stars between the first two bars are of the second type; 
 
**|***||*|
Here's an example with n=6
and k=5. We're getting 2 of the first type, 3 of the second type, 0 of the third type, 1 of the fourth type, and 0 of the fifth type.
In order to solve the problem, we just need to reorder the stars and bars by choosing the k1
spots for the bars out of the n+k1 total spots, so our answer is:

(n+k1k1)

((n-k)+k-1)C(k-1) =>  (n-1)C(k-1)  
#include <iostream>
#include<stdio.h>
#include<math.h>
#include<string.h>
using namespace std;

int main() {

    int t,i=0;
    scanf("%d",&t);
    long long int n,k;
    while(t--)
    {
        long long int res=1;
        scanf("%lld%lld",&n,&k);
        if( n-k < (k-1))//Its IMPORTANT! to get accepted
        k=n-k+1;//selecting the smaller value
        if(k==1)
        printf("1\n");
        else
        {
             for(i=1;i<=k-1;i++)
            {
            res=res*(n-i)/(i); 

       /* Dont do res*((n-i)/(i));divide then multiply
        * but instead do res*(n-i)/(i); Its multiply and divide */
            }
        printf("%lld\n",res);
        }
    }
  
    return 0;
}


To calculate nCr , n! will be huge. so we do n*(n-1)*(n-2)...... 
                                                                                                           1   2     3 .....k

8 comments:

  1. Replies
    1. Thanks, let me know if you need any other spoj problem explaination. I will try my best.

      Delete
  2. https://ideone.com/dchwo0 , why its giving WA?

    ReplyDelete
  3. how to perform the same operation with both n and r which can be 10^9 and show the answer in mod 10^9+7???

    ReplyDelete
  4. if( n-k < (k-1))//Its IMPORTANT! to get accepted
    k=n-k+1;//selecting the smaller value



    why this line is important....
    as nCr = nCr-1.....mathematically

    ReplyDelete

SPOJ : MARBLES Solution

Question  MARBLES - Marbles Explaination.... Fill n spaces , with k colors. First select k spaces with k-different color.  Now we are l...