Codeforces Round #665 (Div. 2) A. Distance and Axis

Title
CodeForces 1401 A. Distance and Axis
Time Limit
1 second
Memory Limit
256 megabytes
Problem Description
We have a pointA A A with coordinatex = n x = n x=n onO X OX OX-axis. We’d like to find an integer pointB B B (also onO X OX OX-axis), such that the absolute difference between the distance fromO O O toB B B and the distance fromA A A toB B B is equal tok k k.
Codeforces Round #665 (Div. 2) A. Distance and Axis
文章图片

Since sometimes it’s impossible to find such pointB B B, we can, in one step, increase or decrease the coordinate ofA A A by1 1 1. What is the minimum number of steps we should do to make such pointB B B exist?
Input
The first line contains one integert 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 integersn n n andk k k ( 0 ≤ n , k ≤ 1 0 6 0 \le n, k \le 10^6 0≤n,k≤106) — the initial position of pointA A A and desirable absolute difference.
Output
For each test case, print the minimum number of steps to make pointB B B exist.
Sample Input

6 4 0 5 8 0 1000000 0 0 1 0 1000000 1000000

Sample Onput
0 3 1000000 0 1 0

Note
In the first test case (picture above), if we set the coordinate ofB B B as2 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 moveA A A. So the answer is0 0 0.
In the second test case, we can increase the coordinate ofA A A by3 3 3 and set the coordinate ofB B B as0 0 0 or8 8 8. The absolute difference will be equal to∣ 8 ? 0 ∣ = 8 |8 - 0| = 8 ∣8?0∣=8, so the answer is3 3 3.
Codeforces Round #665 (Div. 2) A. Distance and Axis
文章图片

Source
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可以在轴上的任意整数点)
思路
  • 当 B B B在 A A A点左侧时,可以看做将 ∣ O A ∣ |OA| ∣OA∣划分成两段。
    1. 如果 ∣ O A ∣ |OA| ∣OA∣是奇数,则一定是奇数-偶数得奇数,偶数则一定得偶数
    2. 所以 ∣ O A ∣ |OA| ∣OA∣可以得到 ≤ n \le n ≤n的任意同奇偶性的 k k k
    3. 当不同奇偶性时 可以往右移 1 1 1个单位
  • 当B在A点右侧时
    • 易得答案是 ∣ O A ∣ |OA| ∣OA∣,则结果为 k ? n k-n k?n(k>n时)
【Codeforces Round #665 (Div. 2) A. Distance and Axis】所以答案为 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)
AC代码:
#include using namespace std; typedef long long ll; typedef pair pii; typedef pair 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; }

    推荐阅读