CodeForces 1401 A. Distance and Axis
1 second
256 megabytes
We have a point A A A with coordinate x = n x = n x=n on O X OX OX-axis. We’d like to find an integer point B B B (also on O X OX OX-axis), such that the absolute difference between the distance from O O O to B B B and the distance from A A A to B B B is equal to k k k.
Since sometimes it’s impossible to find such point B B B, we can, in one step, increase or decrease the coordinate of A A A by 1 1 1. What is the minimum number of steps we should do to make such point B B B exist?
The first line contains one integer t t t ( 1 ≤ t ≤ 6000 1 \le t \le 6000 1≤t≤6000) — the number of test cases.
The only line of each test case contains two integers n n n and k k k ( 0 ≤ n , k ≤ 1 0 6 0 \le n, k \le 10^6 0≤n,k≤106) — the initial position of point A A A and desirable absolute difference.
For each test case, print the minimum number of steps to make point B B B exist.
6
4 0
5 8
0 1000000
0 0
1 0
1000000 1000000
0
3
1000000
0
1
0
In the first test case (picture above), if we set the coordinate of B B B as 2 2 2 then the absolute difference will be equal to ∣ ( 2 − 0 ) − ( 4 − 2 ) ∣ = 0 |(2 - 0) - (4 - 2)| = 0 ∣(2−0)−(4−2)∣=0 and we don’t have to move A A A. So the answer is 0 0 0.
In the second test case, we can increase the coordinate of A A A by 3 3 3 and set the coordinate of B B B as 0 0 0 or 8 8 8. The absolute difference will be equal to ∣ 8 − 0 ∣ = 8 |8 - 0| = 8 ∣8−0∣=8, so the answer is 3 3 3.
CodeForces 1401 A. Distance and Axis
O X OX OX轴上给出点 A A A的位置 n n n,和 k k k。
每次操作可以移动A向左或向右一个单位。
求最小操作使得 ∣ ∣ O B ∣ − ∣ A B ∣ ∣ = k ||OB|-|AB||=k ∣∣OB∣−∣AB∣∣=k。(B可以在轴上的任意整数点)
所以答案为 m a x ( i n t ( k % 2 ≠ n % 2 ) , k − n ) max(int(k \% 2 \ne n \% 2), k - n) max(int(k%2=n%2),k−n)
#include
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
const int maxn = 3e5 + 5;
const ll inf = 0x3f3f3f3f;
const ll mod = 1e9 + 7;
#define all(x) x.begin(), x.end()
#define rall(x) x.rbegin(), x.rend()
int main() {
ios::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
int T;
cin >> T;
while (T--) {
int n, k;
cin >> n >> k;
cout << max(int(k % 2 != n % 2), k - n) << endl;
}
return 0;
}