C++ 最长子段和

 最大子段和详解_最大字段和_Niteip的博客-优快云博客

#include <iostream>
#include <sstream>
#include <vector>
#include <string>
#include <algorithm>
#include <climits>
#include <unordered_map>
#include <set>

using namespace std;

vector<int> read_line_data();
vector<int> read_line_data(char split);
void output_data(const vector<int>& data);

int main() {
    vector<int> a = read_line_data(',');
    int n = a.size();
    vector<int> b(n, 0);
    int max_v = INT_MIN;
    int left = 0;
    int right = 0;
    b[0] = a[0];
    for (int i = 1; i < n; i++) {
        if (b[i - 1] >= 0) {
            b[i] = b[i - 1] + a[i];
        } else {
            b[i] = a[i];
            left = i;
        }
        if (max_v < b[i]) {
            max_v = b[i];
            right = i;
        }
    }

    cout << max_v << " " << left << " " << right << endl;

}

vector<int> read_line_data() {
    string src;

    getline(cin, src);
    istringstream iss(src);

    vector<int> data;
    int token;
    while (iss >> token) {
        data.push_back(token);
    }

    return data;
}

vector<int> read_line_data(char split) {
    string input;

    cin >> input;
    vector<int> data;
    stringstream ss(input);
    string token;
    while (getline(ss, token, split)) {
        int value = stoi(token);
        data.push_back(value);
    }

    return data;
}

void output_data(const vector<int>& data) {
    int n = data.size();
    for (int i = 0; i < n; i++) {
        cout << data[i] << " ";
    }
}

 

### 蓝桥杯 C++ 最长序列 动态规划 解题思路 #### 一、最长递增序列问题概述 在蓝桥杯竞赛中,最长递增序列(Longest Increasing Subsequence, LIS)是一个常见的动态规划问题。该类问题旨在给定数组中找到一个尽可能长的序列,使得这个序列中的元素严格按升序排列[^1]。 #### 二、解题方法分析 对于LIS问题,在C++编程环境下采用动态规划算法解决时,可以定义`dp[i]`表示以第i个数结尾的最大递增序列长度,则状态转移方程可写作: 当遍历到位置j<i且nums[j]<nums[i]时更新 `dp[i]=max(dp[i], dp[j]+1)`;初始化每个`dp[]`值为1因为最短也是它自己单独构成的一个序列[^2]。 为了优化时间复杂度至O(n log n),还可以引入辅助数据结构如树状数组或者使用二分查找来替代朴素做法中的线性扫描过程用于维护当前最优解的信息[^3]。 ```cpp #include <iostream> #include <vector> #include <algorithm> using namespace std; int lengthOfLIS(vector<int>& nums) { vector<int> d; for(int num : nums){ auto it = lower_bound(d.begin(),d.end(),num); if(it != d.end()) *it=num; else d.push_back(num); } return d.size(); } // 测试函数 void test(){ vector<int> nums={10,9,2,5,3,7,101,18}; cout<<lengthOfLIS(nums)<<endl; } ``` 此段代码实现了上述提到的时间复杂度更低的方法,通过不断更新有序列表`d`达到目的,并最终返回其大小作为答案。 #### 三、具体实例应用 考虑到实际比赛场景下的题目可能更加灵活多变,除了标准形式外还可能出现带有额外条件约束的情况。因此建议参赛者不仅要掌握基础理论知识,还需要积累更多实战经验并熟悉不同类型的变形题目处理方式。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值