传送门
A. Distance and Axis
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output
We have a point Awith coordinate x=n on OX-axis. We’d like to find an integer point B (also on OX-axis), such that the absolute difference between the distance from O to B and the distance from A to B is equal to k
The description of the first test case.Since sometimes it’s impossible to find such point B, we can, in one step, increase or decrease the coordinate of A by 1. What is the minimum number of steps we should do to make such point Bexist?
Input
The first line contains one integer t(1≤t≤6000) — the number of test cases.
The only line of each test case contains two integers n and k (0≤n,k≤106) — the initial position of point A and desirable absolute difference.
Output
For each test case, print the minimum number of steps to make point B
exist.
Example
Input
6
4 0
5 8
0 1000000
0 0
1 0
1000000 1000000
Output
0
3
1000000
0
1
0
Note
In the first test case (picture above), if we set the coordinate of B
as 2 then the absolute difference will be equal to |(2−0)−(4−2)|=0 and we don’t have to move A. So the answer is 0.In the second test case, we can increase the coordinate of Aby 3 and set the coordinate of B as 0 or 8. The absolute difference will be equal to |8−0|=8, so the answer is 3
题意:输入t组测试样例,输入A在X轴的坐标,以及k的大小;在x轴上有一个点A,坐标是x=n。我们想找到一个整数点B(也在x轴上),使从O到B的距离和从A到B的距离之差的绝对值等于k。因为有时候找点B是不可能的,我们可以一步,把A的坐标增加或减少1。使B点存在的最小步骤数是多少?
思路:首先判断n与k的大小关系,后判断对2求余即可。如果 n小 于 k ,则必须将A移至坐标k,并将B的坐标设置为0或k。 因此答案是k−n。
如果 n不小于 k,则将B的坐标定义m(m×2≤n) 根据问题中的条件,(m−0)和(n−m)之间的差应等于k。 即(n−m)−(m−0)是k,并且总结公式 m=(n−k)/2 。 因为B的坐标是整数,所以如果n和k的奇偶性相同,则答案为0,否则答案为1(如果将A的坐标增加1,则m变为整数)。具体看代码。
AC代码
#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
int t;
long n,k;
cin>>t;
while(t--)
{
cin>>n>>k;
if(n==k)
{
cout<<0<<endl;
}
else if(n<k)
{
cout<<k-n<<endl;
}
else
{
cout<<((n-k)%2==0?0:1)<<endl;
}
} return 0;
}