Menu Close

Find out what is the minimum possible energy he needs to spend.

Oh, no! Shahid in trouble. He’s got himself stuck in a cave (we don’t know how) and is looking for a way out.
The bigger problem is that he needs to get his tractor out of the cave (don’t ask why Shahid owns a tractor!). He currently faces a large block of height N cells and length N cells, and needs to get his tractor across this block. 

The block is made up of vertical columns of soil, each of which is one cell long. Each column has a continuous vertical gap, with the ith column having its gap from the lith cell to the hith cell (starting from the bottom, 0-indexing). 

That is, in the ith column, there is no soil from the lith cell to the hith cell (both inclusive). 

Shahid can build additional gaps by clearing some cells of soil. His tractor has height H, and therefore, he needs to build a horizontal corridor of height H passing through all the columns. That is, some consecutive H rows must have no soil. Please see the figures in the example and explanation sections for more details.
Shahid is able to clear one cell of soil by spending one unit of energy. 

Shahid is smart, and will figure out a way to build the horizontal corridor while spending the minimum possible amount of energy. 

find out what is the minimum possible energy he needs to spend.

Input:
First line of input contains one integer T - number of test cases. T test cases follow.

Each test case starts with two integers N and H – size of the cave and height of the tractor, respectively. 

In each of the next N lines are two integers li and hi, respectively indicating lowest and highest number of cell for the gap in the ith column.


Output:
Print a single integer representing minimum energy required.

#include <stdio.h>
long long p[1000005][2];
int main()
{
 int t;
 long n,h,i,a,b;
 register int c;
 scanf("%d",&t);
 while(t--)
 {
 scanf("%ld %ld",&n,&h);
 for(i=0;i<n;i++)
 p[i][0]=p[i][1]=0;
 for(i=0;i<n;i++)
 {
 scanf("%ld %ld",&a,&b);
 p[a][0]++;
 p[b][1]++;
 }
 for(i=0;i<n;i++)
 p[i+1][0]=p[i+1][0]+(p[i][0]-p[i][1]);
 for(i=0;i<n;i++)
 p[i][0]+=p[i-1][0];
 c=p[h-1][0];
 for(i=0;i<n;i++)
 {
 if(c<p[i][0]-p[i-h][0])
 c=p[i][0]-p[i-h][0];
 }
 printf("%lld\n",(long long)h*n-c);
 }
return 0;
}

INPUT_1:
1
6  3
3  2
2  4
1  5
3  5
1  4
2  2

OUTPUT:
6


INPUT_2:
2
4  2
1  2
2  1
1  3
3  3
5  4
4  3
3  4
2  3
3  1
1  2

OUTPUT:
4
15


ILLUSTRATION (MIND BOGGLING)

Executed using gcc

Morae Q!