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;
}
posted @ 2021-07-21 14:21  糖豆爸爸  阅读(331)  评论(0编辑  收藏  举报
Live2D