# 題目: UVa 10642 - Can You Solve It
# 題目說明
給一個平面座標的移動規則
(0, 0) -> (0, 1) -> (1, 0) -> (0, 2) -> (1, 1) -> (2, 0) -> (0, 3) ...以此類推
求初始座標(x1, y1)與目的座標(x2, y2)的距離
INPUT:
第一行輸入一個整數t,代表測資數
接下來有t行,每行有4個整數x1、y1、x2、y2,代表初始座標(x1, y1)與目的座標(x2, y2)
OUTPUT:
輸出從初始座標(x1, y1)到目的座標(x2, y2)的距離
# 解題方法
使用一個變數cnt紀錄距離
先將初始座標(x1, y1)移至y軸上,也就是x1歸零,cnt減去移動的距離
再將目的座標(x2, y2)移至y軸上,也就是x2歸零,cnt加上移動的距離
最後再算(0, y1)到(0, y2)的距離,公式為y1 + 1累加至y2
假設現在要從(1, 2)移動到(3, 4)
將初始座標(1, 2)往左移變成(0, 3),cnt為0 - 1 = -1
將目的座標(3, 4)往左移3次,變成(0, 7),cnt為-1 + 3 = 2
現在問題變成要將(0, 3)移動到(0, 7),按照公式需要加4, 5, 6, 7,所以cnt為2 + 4 + 5 + 6 + 7 = 24
# 參考程式碼
#include <iostream>
using namespace std;
static auto fast_io = []
{
ios::sync_with_stdio(false);
cout.tie(nullptr);
cin.tie(nullptr);
return 0;
}();
int main()
{
int t, x1, y1, x2, y2;
int Case = 0;
cin >> t;
while (t--)
{
int cnt = 0;
cin >> x1 >> y1 >> x2 >> y2;
while (x1) --x1, ++y1, --cnt;
while (x2) --x2, ++y2, ++cnt;
for (int i = y1 + 1; i <= y2; ++i) cnt += i;
cout << "Case " << ++Case << ": " << cnt << "\n";
}
}