使用C++,獲取軸一側剩餘點的最小移除點數。
問題描述
笛卡爾平面上給定 N 個點。我們的任務是找出應該移除的最小點數,以便將剩餘的點置於任意軸的一側。
如果給定的輸入是 {(10, 5), (-2, -5), (13, 8), (-14, 7)},那麼如果我們移除 (-2, -5),所有剩餘的點都在 X 軸之上。
因此答案是 1。
演算法
1. Finds the number of points on all sides of the X-axis and Y-axis 2. Return minimum from both of them
例子
#include <iostream>
#include <algorithm>
#define SIZE(arr) (sizeof(arr) / sizeof(arr[0]))
using namespace std;
struct point{
int x, y;
};
int minPointsToBeRemoved(point arr[], int n){
int a = 0, b = 0, c = 0, d = 0;
for (int i = 0; i < n; i++){
if (arr[i].x >= 0)
b++;
else if (arr[i].x <= 0)
a++;
if (arr[i].y <= 0)
d++;
else if (arr[i].y >= 0)
c++;
}
return min({a, d, c, b});
}
int main(){
point arr[] = {{10, 5}, {-2, -5}, {13, 8}, {-14, 7}};
cout << "Minimum points to be removed = " <<
minPointsToBeRemoved(arr, SIZE(arr)) << endl;
return 0;
}輸出
當你編譯和執行上述程式時。它將生成以下輸出 -
Minimum points to be removed = 1
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP