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 drawn
stars in a row to represent the cakes, andk−1 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;
n=6
andk=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 thek−1
spots for the bars out of then+k−1 total spots, so our answer is:
(n+k−1k−1)
((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
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
stars in a row to represent the cakes, and
**|***||*|
Here's an example with and
In order to solve the problem, we just need to reorder the stars and bars by choosing the
spots for the bars out of the
((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