用 C++ 統計二維空間中滿足給定條件的三元組點對 (A, B, C)


給定二維空間中的 N 個點作為輸入。目標是找到輸入中滿足以下條件的三元組點的數量:其中一點是另外兩點連線的中點。例如,如果三元組是 (A,B,C),則 B 是 A 和 C 的中點(或 A、B、C 的任何其他組合)。

我們將透過將所有點作為 <int,int> 對插入向量來實現這一點。然後將該向量中的所有對新增到集合中。透過從集合中取兩點,檢查 (x,y) 座標的和除以 2 是否存在於同一集合中。如果是,則遞增三元組計數。

讓我們透過例子來理解。

輸入 

{ 1,2 }, { 4,2} , { 2,1 } , { 7,2 } N=4 pairs

輸出 

Count of triplet pairs that satisfy the given condition are: 1

說明 

Here {4,2} is mid-point between {1,2} and {7,2}. Only 1 such triplet

輸入 

{ 1,2 }, { 4,2} , { 2,1 } , { 5,2 }, { 8,1} , {1,1} N=6

輸出 

Count of triplet pairs that satisfy the given condition are: 1

說明 

No such triplet exist

下面程式中使用的方案如下:

  • 我們使用一個 <int,int> 型別對的向量。

  • 每對包含 (x,y) 座標。

  • 函式 mid_point(vector<pair<int, int>> vec, int size) 將向量及其大小作為輸入,並返回滿足中點條件的三元組數量。

  • 將初始變數 count 初始化為 0,用於統計此類三元組。

  • 將向量中的所有對插入到集合 <pair<int, int> > sets 中。它將包含所有唯一點。

  • 使用兩個 for 迴圈遍歷向量中的每對點。

  • 將兩點的 x 座標之和儲存在整數 point_A 中,將兩點的 y 座標之和儲存在整數 point_B 中。

  • 如果 point_A 和 point_B 中這兩個和都是偶數,則檢查中點條件。

  • 如果一對 (point_A/2,point_B/2) 作為對存在於集合中,則表示存在中點。遞增三元組計數。

  • 最後,count 將包含三元組的數量。

  • 在 for 迴圈結束時返回 count 作為結果。

示例

 線上演示

#include <bits/stdc++.h>
using namespace std;
int mid_point(vector<pair<int, int>> vec, int size){
   int count = 0;
   set<pair<int, int> > sets;
   for (int i = 0; i < size; i++){
      sets.insert(vec[i]);
   }
   for (int i = 0; i < size; i++){
      for (int j = i + 1; j < size; j++){
         int point_A = vec[i].first + vec[j].first;
         int point_B = vec[i].second + vec[j].second;
         if (point_A % 2 == 0 && point_B % 2 == 0){
            if (sets.find(make_pair(point_A / 2, point_B / 2)) != sets.end()){
               count++;
            }
         }
      }
   }
   return count;
}
int main(){
   vector<pair<int, int>> vec = { { 9, 2 }, { 5, 2 }, { 1, 2 } };
   int size = vec.size();
   cout<<"Count of triplet pairs (A, B, C) of points in 2-D space that satisfy the given condition are: "<<mid_point(vec, size);
}

輸出

如果我們執行上面的程式碼,它將生成以下輸出:

Count of triplet pairs (A, B, C) of points in 2-D space that satisfy the given condition are: 1

更新於:2020-10-31

241 次檢視

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告