先附上自己最开始写的版本,思路就是暴力遍历
时间复杂度O(n^2)理所当然的超时了QWQ
#include <iostream>
#include <vector>
#include <stack>
#include <string>
#include <time.h>
#include <queue>
#include <cstring>
#include <set>
#include <map>
#include <algorithm>
#include <numeric>
using namespace std;
int Weightest(vector<int>& weight,int n)
//取走货物的分割点设为0,遍历所有货物,计算最大区间和
{
weight[n-1]=0;
int temp=0,res=0;
for(int i=0;i<weight.size();i++)
{
if(weight[i]==0)
{
res=res>temp?res:temp;
temp=0;
}
else
{
temp+=weight[i];
}
if(i==weight.size()-1)
//遍历到最后一件货物比较当前区间和与当前最大区间和
{
res=res>temp?res:temp;
}
}
return res;
}
int main()
{
int i, n,temp;
cin >> n;
if(n==0) return 0;
vector<int> wei(n);
for (i = 0; i < n; i++)
{
cin>>temp;
wei[i]=temp;
}
for (i = 0; i < n; i++)
{
cin>>temp;
cout<<Weightest(wei,temp)<<endl;
}
system("pause");
return 0;
}
再来看参考自高赞第一篇题解的解法,成功AC。感谢大佬
主要难点在于怎样降低每次分割后搜寻最大区间和的时间复杂度,以下代码通过使用前缀和数组以及两种有序容器即set与map分别保存分割点和区间和使得时间复杂度由常规顺序遍历的n降低为logN(有序容器的查找、插入和删除操作均摊为 logN)
LeetCode参考题解
#include <iostream>
#include <vector>
#include <stack>
#include <string>
#include <time.h>
#include <queue>
#include <cstring>
#include <set>
#include <map>
#include <algorithm>
#include <numeric>
using namespace std;
int prefix[50050];
std::map<int, int> mmap;//map用于保存区间和的值,默认升序
std::set<int> bound;//set用于存储分割点,默认升序
int main() {
int n;
scanf("%d", &n);
int w;
memset(prefix, 0, sizeof(prefix));//初始化函数
for (int i = 0; i < n; i++) {
scanf("%d", &w);
prefix[i + 1] = prefix[i] + w;
}
int pos;
//初始化左右边界为数组边界
bound.insert(0);
bound.insert(n + 1);
for (int i = 0; i < n; i++) {
scanf("%d", &pos);
auto idx = bound.lower_bound(pos);
// 由于 set 的迭代器只能自减,所以先给 right 赋值
int right = *idx, left = *(--idx);//找到分割点的左右边界
int seg = prefix[right - 1] - prefix[left];
//分割之前先把map里面保存的分割前的区间和清除或减一(存在多个相等和的区间时)
if (mmap.find(seg) != mmap.end()) {
if (mmap[seg] == 1) {
mmap.erase(seg);
} else {
mmap[seg]--;
}
}
//分割后保存新增的两个区间和
int left_sum = prefix[pos - 1] - prefix[left];
int right_sum = prefix[right - 1] - prefix[pos];
//保存分割点
bound.insert(pos);
mmap[left_sum]++;
mmap[right_sum]++;
printf("%d\n", mmap.rbegin()->first);
//map默认升序,返回尾端值
}
return 0;
}