zoukankan      html  css  js  c++  java
  • P1614 爱与愁的心痛题解

    题目传送门

    一、两层暴力循环法

    #include <bits/stdc++.h>
    
    using namespace std;
    const int N = 3010;
    const int INF = 0x3f3f3f3f;
    typedef long long LL;
    int a[N];
    LL MIN = INF;
    
    int main() {
        int n, m;
        //n = 10,m = 3
        cin >> n >> m;
        for (int i = 1; i <= n; i++) cin >> a[i];
    
        for (int i = 1; i <= n - m + 1; i++) {
            LL sum = 0;
            for (int j = 0; j < m; j++) sum += a[i + j];
            MIN = min(MIN, sum);
        }
        cout << MIN << endl;
        return 0;
    }
    

    二、滑动窗口法

    #include <bits/stdc++.h>
    
    using namespace std;
    const int N = 3010;
    int a[N];
    int MIN;
    
    int main() {
        //滑动窗口思想
        int n, m;
        cin >> n >> m;
        for (int i = 1; i <= n; i++) cin >> a[i];
    
        //第一组m个数
        int sum = 0;
        for (int i = 1; i <= m; i++) sum += a[i];
        MIN = sum;//第一组数的和是默认值
    
        //滑动窗口,加入下一个数字,减去顶部的数字
        for (int i = m + 1; i <= n; i++) {
            sum = sum + a[i] - a[i - m];
            //不断的取min,找出和的最小值
            MIN = min(MIN, sum);
        }
        //输出最小值
        printf("%d", MIN);
        return 0;
    }
    

    三、一维前缀和

    #include <bits/stdc++.h>
    
    using namespace std;
    const int N = 3010;
    const int INF = 0x3f3f3f3f;
    int s[N], a[N];
    int n, m;
    int MIN = INF;
    
    int main() {
        cin >> n >> m;
        for (int i = 1; i <= n; i++) {
            cin >> a[i];//刺痛值
            s[i] = s[i - 1] + a[i];//构建一维前缀和
        }
    
        for (int i = m; i <= n; i++)
            MIN = min(MIN, s[i] - s[i - m]);//求定区间和并取最小的一部分
        //输出最小值
        printf("%d", MIN);
        return 0;
    }
    
  • 相关阅读:
    python 适配器
    python 装饰器
    实测 《Tensorflow实例:利用LSTM预测股票每日最高价(二)》的结果
    TFRecord 存入图像和标签
    TFRecord 读取图像和标签
    CONDA常用命令
    sotfmax的通俗理解
    sigmoid的通俗理解
    查看日志,定位错误_常用的操作
    工作中Git实操详解_看完这篇直接上手!
  • 原文地址:https://www.cnblogs.com/littlehb/p/15039302.html
Copyright © 2011-2022 走看看