【PTA刷题】前缀和算法(快速求连续区间和)

2020甲级秋季考试:How Many Ways to Buy a Piece of Land

**前缀和用法:用来快速算出某个数列的连续子列的和。 **

输入:
给你N个数和一个阈值K;
每次只能选中相邻的一块数字,且这块区域的和不能大于阈值。
问你有多少种旋转方法。

5 85
38 42 15 24 9

输出:

11

/*输出解析:
38
42
15
24
9
38 42
42 15
42 15 24
15 24
15 24 9
24 9
*/

代码参考:https://www.acwing.com/file_system/file/content/whole/index/content/1493430/

#include <iostream>
#include <cstring>

using namespace std;
const int N = 10010;
int p[N];

int main()
{
    
    
    int m, sum;
    cin >> m >> sum;
    for(int i = 1; i <= m; i++) 
    {
    
    
        cin >> p[i];
        p[i] = p[i] + p[i - 1];   //!!!!!!重点!!!!!!  维护一个前缀和数组,数组内每一格的sum都是前i个数的和
    }
    int cnt = 0;
    for(int i = 0; i < m; i++)
    {
    
    
        for(int j = i + 1; j <= m; j++)
        {
    
    
            //printf("%d %d %d\n", p[j] - p[i], p[j], p[i]);
            if (p[j] - p[i] <= sum) cnt++;
            else break;
        }
    }
    printf("%d", cnt);
}

猜你喜欢

转载自blog.csdn.net/abyss_miracle/article/details/110570389