C++ 程式碼用於查詢滿足約束條件的點
假設我們有兩個點 a = (x1, y1) 和 b = (x2, y2)。兩個點之間的曼哈頓距離 dist(a, b) = |x1 - x2| + |y1 - y2|。如果點 a 的座標是 (0, 0) 且點 b 的座標是 (x, y),我們必須找到一個點 c,使得 dist(a, c) = dist(a, b)/ 2 且 dist(b, c) = dist(a, b)/2。如果找不到這樣的點,則列印 -1, -1。
所以,如果輸入為 x = 13,y = 7,那麼輸出將為 6, 4。
步驟
要解決此問題,我們將遵循以下步驟 -
if x mod 2 is same as 0 and y mod 2 is same as 0, then: print( x / 2, y / 2) otherwise when (x + y) mod 2 is same as 1, then: print(- 1, - 1) Otherwise, print(x / 2, (y + 1) / 2)
示例
讓我們看看以下實現,以獲得更好的理解 -
#include <bits/stdc++.h> using namespace std; #define N 100 void solve(int x, int y) { if(x % 2 == 0 && y % 2 == 0) cout<< x / 2 <<' '<< y / 2 <<endl; else if((x + y) % 2 == 1) cout<< -1 <<' '<< -1 <<endl; else cout<< x / 2 <<' '<< (y + 1) / 2 << endl; } int main() { int x = 13, y = 7 ; solve(x, y); return 0; }
輸入
13, 7
輸出
6 4
廣告