C ++程序找出建筑物的中心坐标和高度

阅读 111 收藏 0 点赞 0 评论 0

假设有一座建筑物,其中心坐标为 xc、yc 和高度 h。我们不知道建筑物的中心坐标,但我们得到了 n 条信息,其中包含 x 和 y 坐标以及高度值 a。坐标 (x, y) 的高度是 (h - |x - xc| - |y - yc|, 0) 的最大值。我们必须找出建筑物的中心坐标和高度。坐标 xi 在数组 x 中给出,yi 在 teg 数组 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

评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号