【发布时间】:2018-06-06 18:25:25
【问题描述】:
这几年Bubble Cup(完结)有问题NEO(我解决不了),问
给定具有 n 个整数元素的数组。我们把它分成几个部分(可能是1个),每个部分是一个连续的元素。在这种情况下,NEO 值通过以下方式计算: 每个部分的值之和。一个部分的值是这个部分中所有元素的总和乘以它的长度。
示例:我们有数组:[ 2 3 -2 1 ]。如果我们将其划分为:[2 3] [-2 1]。那么NEO = (2 + 3) * 2 + (-2 + 1) * 2 = 10 - 2 = 8。
数组中的元素个数小于10^5,并且是-10^6和10^6之间的整数
我尝试过类似分而治之的方法,如果它增加了最大 NEO 数量,则不断地将数组分成两部分,否则返回整个数组的 NEO。但不幸的是,该算法具有最坏情况 O(N^2) 复杂度(我的实现如下)所以我想知道是否有更好的解决方案
编辑:我的算法(贪婪)不起作用,例如 [1,2,-6,2,1] 我的算法返回整个数组,而要获得最大的 NEO 值是参加 [1,2],[-6],[2,1] 的部分,它给出的 NEO 值为 (1+2)*2+(-6)+(1+2)*2=6
#include <iostream>
int maxInterval(long long int suma[],int first,int N)
{
long long int max = -1000000000000000000LL;
long long int curr;
if(first==N) return 0;
int k;
for(int i=first;i<N;i++)
{
if(first>0) curr = (suma[i]-suma[first-1])*(i-first+1)+(suma[N-1]-suma[i])*(N-1-i); // Split the array into elements from [first..i] and [i+1..N-1] store the corresponding NEO value
else curr = suma[i]*(i-first+1)+(suma[N-1]-suma[i])*(N-1-i); // Same excpet that here first = 0 so suma[first-1] doesn't exist
if(curr > max) max = curr,k=i; // find the maximal NEO value for splitting into two parts
}
if(k==N-1) return max; // If the max when we take the whole array then return the NEO value of the whole array
else
{
return maxInterval(suma,first,k+1)+maxInterval(suma,k+1,N); // Split the 2 parts further if needed and return it's sum
}
}
int main() {
int T;
std::cin >> T;
for(int j=0;j<T;j++) // Iterate over all the test cases
{
int N;
long long int NEO[100010]; // Values, could be long int but just to be safe
long long int suma[100010]; // sum[i] = sum of NEO values from NEO[0] to NEO[i]
long long int sum=0;
int k;
std::cin >> N;
for(int i=0;i<N;i++)
{
std::cin >> NEO[i];
sum+=NEO[i];
suma[i] = sum;
}
std::cout << maxInterval(suma,0,N) << std::endl;
}
return 0;
}
【问题讨论】:
-
only 在这里得到 O(n^2) 会很不错:蛮力是 O(n 2^n),来自 compositions 的数量>n.
-
你的时间复杂度不是 O(n^2),很遗憾
-
是数组的所有部分长度相同还是长度任意?
-
@Yola 我刚刚找到了一个反例,如果我采用 1 2 -6 2 1 我的算法会选择给出 0*6 = 0 的整个数组,而最佳值是 [1,2],[ -6],[2,1] = (1+2)*2+(-6)+(2+1)*2=6。回到绘图板我猜:P
-
感谢您的更新。我尝试了动态编程方法,但它需要大量内存和失败的时间限制。