检查一条45度线是否可以将平面分成两个重量相等的部分(使用C++)
假设我们有n个不同的二维坐标点(Xi, Yi),每个点都有一个权重Wi,我们必须检查是否可以绘制一条45度角的线,使得每个侧面的点权重之和相同。
所以,如果输入类似于[[-1,1,3],[-2,1,1],[1,-1,4]],则输出为True。
为了解决这个问题,我们将遵循以下步骤:
- n := v的大小
- 定义一个映射weight_at_x
- max_x := -2000, min_x := 2000
- for i := 0 to n-1 do:
- temp_x := v[0, i] - v[1, i]
- max_x := max(max_x, temp_x)
- min_x := min(min_x, temp_x)
- weight_at_x[temp_x] := weight_at_x[temp_x] + v[2, i]
- 定义一个数组sum_temp
- 在sum_temp末尾插入0
- for x := min_x to max_x do:
- 在sum_temp末尾插入(sum_temp的最后一个元素 + weight_at_x[x])
- total_sum := sum_temp的最后一个元素
- partition_possible := false
- for i := 1 to sum_temp的大小-1 do:
- if sum_temp[i] == total_sum - sum_temp[i] then:
- partition_possible := true
- if sum_temp[i - 1] == total_sum - sum_temp[i] then:
- partition_possible := true
- if sum_temp[i] == total_sum - sum_temp[i] then:
- return partition_possible
示例
让我们看看下面的实现,以便更好地理解:
#include <bits/stdc++.h>
using namespace std;
void is_valid_part(vector<vector<int>> &v){
int n = v.size();
map<int, int> weight_at_x;
int max_x = -2000, min_x = 2000;
for (int i = 0; i < n; i++) {
int temp_x = v[0][i] - v[1][i];
max_x = max(max_x, temp_x);
min_x = min(min_x, temp_x);
weight_at_x[temp_x] += v[2][i];
}
vector<int> sum_temp;
sum_temp.push_back(0);
for (int x = min_x; x <= max_x; x++) {
sum_temp.push_back(sum_temp.back() + weight_at_x[x]);
}
int total_sum = sum_temp.back();
int partition_possible = false;
for (int i = 1; i < sum_temp.size(); i++) {
if (sum_temp[i] == total_sum - sum_temp[i])
partition_possible = true;
if (sum_temp[i - 1] == total_sum - sum_temp[i])
partition_possible = true;
}
printf(partition_possible ? "TRUE" : "FALSE");
}
int main() {
vector<vector<int>> v = {{-1,1,3},{-2,1,1},{1,-1,4}};
is_valid_part(v);
}输入
{{-1,1,3},{-2,1,1},{1,-1,4}}输出
TRUE
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP