C++程式找出建築物的中心座標和高度
假設,有一棟建築物,其中心座標為xc、yc,高度為h。我們不知道建築物的中心座標,但我們提供了n條資訊,其中包含x和y座標以及高度值a。座標(x, y)的高度是(h - |x - xc| - |y - yc|, 0)的最大值。我們必須找出建築物的中心座標和高度。座標xi在陣列x中給出,yi在陣列y中給出,ai在陣列a中給出。
因此,如果輸入類似於n = 3,x = {3, 3, 2},y = {4, 2, 3},a = {6, 6, 6},則輸出將為3 3 7。
中心座標為3,3,建築物的高度為7。
步驟
為了解決這個問題,我們將遵循以下步驟:
check := true for initialize xc := 0, when xc <= 100, update (increase xc by 1), do: for initialize yc := 0, when yc <= 100, update (increase yc by 1), do: check := true mh := 2000000000 h := -1 for initialize i := 0, when i < n, update (increase i by 1), do: k := |(x[i] - xc) + |y[i] - yc|| if a[i] is same as 0, then: mh := minimum of mh and k else: if h < 0, then: h := a[i] + k otherwise when h is not equal to a[i] + k, then: check := false Come out from the loop if h > mh, then: check := false Ignore following part, skip to the next iteration if check is non-zero, then: Come out from the loop if check is non-zero, then: Come out from the loop print(xc, yc, h)
示例
讓我們看看以下實現以獲得更好的理解:
#include <bits/stdc++.h>
using namespace std;
void solve(int n, vector<int> x, vector<int> y, vector<int> a){
bool check = true;
int xc, yc, h;
for (xc = 0; xc <= 100; xc++) {
for (yc = 0; yc <= 100; yc++) {
check = true;
int k, mh = 2e9;
h = -1;
for(int i = 0; i < n; i++) {
k = abs(x[i] - xc) + abs(y[i] - yc);
if (a[i] == 0) {
mh = min(mh, k);
} else {
if (h < 0) {
h = a[i] + k;
} else if (h != a[i] + k) {
check = false;
break;
}
}
}
if (h > mh) {
check = false;
continue;
}
if (check) {
break;
}
}
if (check) {
break;
}
}
cout << xc << " " << yc << " " << h;
}
int main() {
int n = 3;
vector<int> x = {3, 3, 2}, y = {4, 2, 3}, a = {6, 6, 6};
solve(n, x, y, a);
return 0;
}輸入
3, {3, 3, 2}, {4, 2, 3}, {6, 6, 6}輸出
3 3 7
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP