利用前缀和降维,后面再根据题意利用多重集合快速判断最小力量差就行了(一种dp吧算是)
#include<algorithm>
#include<iostream>
#include<vector>
#include<cmath>
#include<cstring>
#include<stdio.h>
#include<string>
#include<math.h>
#include<set>
using namespace std;
typedef long long ll; // 数据量开long long
ll n; // 存储数组中的元素数量
ll strength[1010] = {0}; // 存储输入的力量值
ll prefix_sum[1010] = {0}; // 存储前缀和,方便快速计算任意子数组的和
multiset<ll> subarray_sums; // 用于存储所有可能的子数组和(多重集合)
int main() {
cin >> n; // 读取元素个数
for (int i = 1; i <= n; i++) {
cin >> strength[i];
prefix_sum[i] = prefix_sum[i - 1] + strength[i];
}
// 存储所有可能的子数组和到多重集合中,方便后续快速查找
for (int left = 1; left <= n; left++) {
for (int right = left + 1; right <= n; right++) {
subarray_sums.insert(prefix_sum[right] - prefix_sum[left]);
}
}
ll min_difference = 9223372036854775807; // 初始化最小差异为最大长整型值(LLONG_MAX)
// 遍历所有的子数组组合,计算最小差异
for (int right = 1; right < n; right++) {
for (int left = 0; left < right; left++) {
ll current_value = prefix_sum[right] - prefix_sum[left];
auto it = subarray_sums.lower_bound(current_value);
if (it != subarray_sums.end()) {
min_difference = min(min_difference, abs(*it - current_value));
}
if (it != subarray_sums.begin()) {
it--;
min_difference = min(min_difference, abs(*it - current_value));
}
}
// 移除已经考察完毕的子数组和
for (int i = right + 1; i <= n; i++) {
subarray_sums.erase(subarray_sums.find(prefix_sum[i] - prefix_sum[right]));
}
}
cout << min_difference << endl; // 输出最小差异
return 0;
}