栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

美团2021校招真题002-小美的仓库整理

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

美团2021校招真题002-小美的仓库整理

先附上自己最开始写的版本,思路就是暴力遍历
时间复杂度O(n^2)理所当然的超时了QWQ

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;
int Weightest(vector& weight,int n)
//取走货物的分割点设为0,遍历所有货物,计算最大区间和
{
    weight[n-1]=0;
    int temp=0,res=0;
    for(int i=0;itemp?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 wei(n);
    for (i = 0; i < n; i++)
    {
        cin>>temp;
        wei[i]=temp;
    }
    for (i = 0; i < n; i++)
    {
        cin>>temp;
        cout< 

再来看参考自高赞第一篇题解的解法,成功AC。感谢大佬
主要难点在于怎样降低每次分割后搜寻最大区间和的时间复杂度,以下代码通过使用前缀和数组以及两种有序容器即setmap分别保存分割点和区间和使得时间复杂度由常规顺序遍历的n降低为logN(有序容器的查找、插入和删除操作均摊为 logN)
LeetCode参考题解

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;

int prefix[50050];
std::map mmap;//map用于保存区间和的值,默认升序
std::set 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("%dn", mmap.rbegin()->first);
        //map默认升序,返回尾端值
    }

    return 0;
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/297878.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号