 Cakewalk

# Problem:

Given N sticks of lengths L, L, … L[N] and a positive integer D.
Two sticks can be paired if the difference of their lengths is at most D.
Pair up as many sticks as possible such that each stick is used at most once.

# Quick Explanation:

Sort the sticks by their lengths and let L be the sorted array.

If L and L cannot be paired, then the stick L is useless.
Otherwise, there exists an optimal pairing where L gets paired with L.

This gives rise to the following algorithm:

``````
numpairs = 0
for ( i = 1; i < N; )
if (L[i] >= L[i+1] -D)  // L and L can be paired
numpairs++,         // pair them up
i += 2;
else
i++;                // eliminate L

``````

# Justifications:

• If L and L cannot be paired then
L < L - D
But, L <= L[i] for every i > 1
So    L < L[i] - D for every i > 1
Hence, L cannot be paired with anyone.

• If L and L can be paired.
Consider any optimal pairing and it can be transformed to a pairing where L and L are paired.
a) If the optimal pairing pairs L with L then we are done.
b) If only one of L and L is paired with someone, then we can replace that pair by (L, L).
c) If both L and L are paired and L is paired with L[n] and L with L[m], then we might as well form pairs (L, L) and (L[n], L[m]).
This is because
L <= L[m] <= L + D
L <= L[n] <= L + D <= L + D
⇒   -D <= L[m] - L[n] <= D

# Setter’s Solution:

Can be found here

# Tester’s Solution:

Can be found here

5 Likes

If L and L cannot be paired then
L < L + D
If L=L+D-1. Then (L-L)=1-D <=D
It should be L<L-D .

@maggu you are right. fixed.

why my solution is giving TLE?
http://www.codechef.com/viewsolution/4361912

//what is wrong with this

#include
#include
#define ll long long
using namespace std;
int main()
{
ll n,d;
cin>>n>>d;
ll a[n];
for(ll i=0;i<n;i++)
cin>>a[i];
sort(a,a+n);
ll cnt=0;
for(ll i=0;i<n;i++)
{
if(a[i+1]-a[i]<=d)
{
cnt++;
i+=1;
}

``````}
cout<<cnt<<endl;
return 0;
``````

}

@anichavan20
you are accessing nth element of array,
which is throwing some garbage value…

when i=n-1,you try to compute a[n]-a[n-1]…

solve this…
you may try this http://www.codechef.com/viewsolution/4361912

https://www.codechef.com/viewsolution/12375437