Nate likes to use elevator while being at a building. On his father’s office, there are 3 identical elevators (which have same velocity 1 level/second). Unfortunately, one of those elevators is in maintenance. Then, when Nate sees those two elevators, the first one is on the x floor going up and the second one is on the y floor and is going down. The third elevator (which in maintenance) is recently on the k floor. Nate is wondering if those three elevators will be in the same level or not.
Format input: Input consists of 3 integers x, y, k, the position of the first, second, and third elevator, respectively.
Format output: Output a line consists of t which describe the time when the three elevators are on the same levels. If this event is impossible to happen, output -1.
Constraints: 0 ≤ x, y, k ≤ 100
Sample input 1 (user input):
3 5 4
Sample output:
1
Sample input 2 (user input):
1 2 5
Sample output:
-1
This is my code:
#include <stdio.h>
int main()
{
int x, y ,k;
scanf("%d %d %d", &x, &y, &k);
while(x >= k && y <= k)
{
if(x-k == k-y || k-x == y-k)
{
if(x < k)
{
printf("%d\n", k-x);
}
else if(k <= x)
{
printf("%d\n", x-k);
}
}
else if(x == y)
{
if(x > k)
{
printf("%d\n", x-k);
}
else if(x <= k)
{
printf("%d\n", k-x);
}
}
else
{
printf("-1\n");
}
x++;
y--;
}
return 0;
}
My answer is incorrect when I submit it to the Online Judge, I think it's because if I input 2 6 4, the output is supposed to be 2, since they need 2 seconds for all the elevators to be on the same level, but my code's output is -1. Can anyone help me with this problem?