4422. Boat Game
Description
Mirko has recently discovered an old video game. The screen of this game is divided into N columns.
At the bottom of the screen, there is an M-columns-wide boat (M<N). The player can move this boat left or right during the game, but the boat must remain completely within the screen at all times. The boat initially occupies the leftmost M columns.
Apples are being dropped from the top of the screen. Each apple starts its fall at the top of one of the N columns, falling straight down until it reaches the bottom of the screen. The next apple starts its fall just after the current one has reached the bottom.
An apple is said to be picked up if the boat is placed so that it occupies the column down which the apple is falling when it reaches the bottom. The goal of the game is to pick up all of the apples, in a way that minimizes the distance that the boat must travel.
Input
The first line contains an integer T(1<=T<=10)- indicating the number of test cases.
For each case, the first line contains two integers N and M(1<=M < N <= 10).The second line of input contains an integer J(1<=J<=20), the number of falling apples. The following J lines contain the column positions of those apples, in the order in which they will fall.
Output
One line for each case, each line contains an integer indicating the minimal distance that the boat must travel in order to pick up all the apples.
Sample Input
2 5 1 3 1 5 3 5 2 3 1 5 3
Sample Output
6
4
#include <iostream>
using namespace std;
int main()
{
int t;
cin>>t;
while(t--)
{
int n,m,j,goal[22]={0},boat[2]={1,1};
cin>>n>>m>>j;
for(int i=1;i<=j;i++)
cin>>goal[i];
int count=0;
boat[1]=m;
for(int i=1;i<=j;i++)
{
if(goal[i]>=boat[0]&&goal[i]<=boat[1]) continue;
if(goal[i]<boat[0])
{
int temp=boat[0]-goal[i];
count+=temp;
boat[0]=goal[i];
boat[1]=goal[i]+m-1;
}
if(goal[i]>boat[1])
{
int temp=goal[i]-boat[1];
count+=temp;
boat[1]=goal[i];
boat[0]=goal[i]-m+1;
}
}
cout<<count<<endl;
}
return 0;
}