 # Need help, Combinatorics problem

The question goes like this… given n coins 1,2,3…n kept in a row. You have to pick M coins from these N coins such that C connected components are left

A part [a,b] of sequence is called a connected component if for all a <= i <= b there is a coin at position i and also there are no marbles at positions a-1 and b+1 (either because those marbles have been removed or because they are out of range [1,N] ).

My approach is this:
Lets assume that the ith connected component has xi coins in it. Now some of all the left out coins should be n-m. So the equation we get is :-
`x1+x2+x3......xC=n-m`

Then i just took the positive solutions of this equation as my final answer.
Apparently this method is wrong and I am not able to figure it out why.

Consider a simple test case
`3 2 1`
The equation you’ll get is x_{1}=1…So, according to this your answer should be 1 as x_{1}=1 is the only possible solution but you can remove 2 marbles out of 3 in 3\choose 2 ways and in either of the ways, you’ll get 1 connected component. So, answer for this case should be 3 and not 1.

I see. Can you please also provide some other alternative to solve this problem?

First you can notice that the marbles will be in the form `efefefefefe....fe`, where e denotes a component with no marbles and f denotes a component with marbles. We have to distribute n-m marbles in c f’s. Each f must have at least one marble, so it is equivalent to distributing n-m-c marbles in c fs. For the e’s, all the e’s except the first and last must have at least one index without a marble. So we have to distribute m-(c-1) marbles in c+1 e’s. Since the ways to distribute them is independent, we can multiply the answers.

My simple code
``````#include <iostream>
#include <bits/stdc++.h>
#define ll long long int
#define mp make_pair
#define pb push_back
using namespace std;
const ll p =1e9 + 7;
//Precomputation
ll modpower(ll base, ll power, ll mod=p){
ll ans =1;
base%=p;
while(power){
if(power&1){
ans*=base;
ans%=p;
}
base*=base;
base%=p;
power>>=1;
}
return ans;
}
vector<ll> fact;
vector<ll> invfact;
void computefactorial(int n){
++n;
fact.resize(n);
invfact.resize(n);
fact=1;
for(int i=1;i<n;i++){
fact[i]=i*fact[i-1];
fact[i]%=p;
}
invfact[n-1]=modpower(fact[n-1],p-2);
for(int i=n-2;i>=0;i--){
invfact[i]=(i+1)*invfact[i+1];
invfact[i]%=p;
}
}
inline ll ncr(int n, int r){
if(n<0 || r>n || r<0){
return 0;
}
return fact[n]*invfact[r]%p * invfact[n-r]%p;
}
//Main code
inline ll objectsinbox(int objects, int boxes){
if(objects==0){
return 1;
}
return ncr(objects + boxes-1, boxes-1);
}
void solve(){
int n,m,c;
cin>>n>>m>>c;
ll ans = objectsinbox(n-m-c, c)*objectsinbox(m-(c-1), c+1);
cout<<ans%p<<"\n";
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t;
cin>>t;
computefactorial(3e5 + 7);
while(t--){
solve();
}
}
``````
1 Like