forked from sitz/UVa-Online-Judge
-
Notifications
You must be signed in to change notification settings - Fork 1
/
10022.cpp
151 lines (147 loc) · 2.36 KB
/
10022.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
#include <bits/stdc++.h>
using namespace std;
#define MAXI(a, b) (a > b ? a : b)
#define MINI(a, b) (a > b ? b : a)
int N, M, N_row, M_row, N_left, M_left, N_right, M_right, MAX;
int Find_R(int n)
{
int k;
k = sqrt((double)n);
if (k * k < n)
{
return k + 1;
}
return k;
}
int Find_L_R(int n, int row)
{
int m, d, k;
m = (row - 1) * (row - 1) + 1;
d = n - m + 1;
k = ceil((double)d / 2);
return k;
}
int Find_R_R(int n, int row)
{
int m, d, k;
m = row * row;
d = m - n + 1;
k = ceil((double)d / 2);
return k;
}
int Dis()
{
if (M_left >= N_left && M_right >= N_right)
{
return 1;
}
return 0;
}
int Distance(int m, int m_r, int n, int n_r)
{
int d = 0, k, dis;
if ((m % 2 && m_r % 2) || (!(m % 2) && !(m_r % 2)))
{
d++;
}
if ((n % 2 && n_r % 2 == 0) || (n % 2 == 0 && n_r % 2 != 0))
{
d++;
}
k = m_r - n_r - 1;
dis = k * 2 + d + 1;
return dis;
}
int LEFT_inside()
{
int d, val, dis, meet_row;
int meet_point;
d = M_left - N_left - 1;
meet_row = M_row - d;
dis = d * 2 + 1;
if ((M_row % 2 == 0 && M % 2 != 0) || (M_row % 2 != 0 && M % 2 == 0))
{
dis++;
meet_row--;
}
meet_point = (meet_row - 1) * (meet_row - 1) + N_left * 2;
val = dis + Distance(meet_point, meet_row, N, N_row);
return val;
}
void Out_side()
{
int meet_point, val;
int d = (M_row - 1) * (M_row - 1);
meet_point = d + N_left * 2;
val = Distance(meet_point, M_row, N, N_row);
val += abs(M - meet_point);
if (val < MAX)
{
MAX = val;
}
d = (M_row) * (M_row);
meet_point = d - N_right * 2 + 1;
val = Distance(meet_point, M_row, N, N_row);
val += abs(M - meet_point);
if (val < MAX)
{
MAX = val;
}
}
void Cal()
{
int temp;
N_row = Find_R(N);
M_row = Find_R(M);
if (N_row == M_row)
{
printf("%d\n", abs(M - N));
return;
}
N_left = Find_L_R(N, N_row);
M_left = Find_L_R(M, M_row);
if (N_left == M_left)
{
printf("%d\n", Distance(M, M_row, N, N_row));
return;
}
N_right = Find_R_R(N, N_row);
M_right = Find_R_R(M, M_row);
if (N_right == M_right)
{
printf("%d\n", Distance(M, M_row, N, N_row));
return;
}
if (Dis() == 1)
{
temp = LEFT_inside();
if (temp < MAX)
{
MAX = temp;
}
}
else
{
Out_side();
}
printf("%d\n", MAX);
}
int main()
{
int a, b;
int kase;
scanf("%d", &kase);
while (kase--)
{
scanf("%d%d", &a, &b);
MAX = 2147483647;
N = MINI(a, b);
M = MAXI(a, b);
Cal();
if (kase)
{
printf("\n");
}
}
return 0;
}