一维差分 C++版本 python版本

AcWing 797 差分  https://www.acwing.com/problem/content/799/

 

#include <iostream>
#include <cstdio>
#include <algorithm>

using namespace std;

const int N = 1e5 + 5;

int a[N], b[N];

void insert(int L, int R, int c)
{
    b[L] += c;
    b[R + 1] -= c;
}

int main()
{
    int n, m;
    cin >> n >> m;
    for(int i = 1; i <= n; ++ i)
    {
        cin >> a[i];
        insert(i, i, a[i]);
    }
    while(m --)
    {
        int L, R, c;
        cin >> L >> R >> c;
        insert(L, R, c);
    }
    for(int i = 1; i <= n; ++ i)
    {
        b[i] += b[i-1];
        cout << b[i] << " ";
    }
}

 

#include <iostream>
#include <cstdio>
#include <algorithm>

using namespace std;

const int N = 1e5 + 5;

int a[N], b[N];

void insert(int L, int R, int c)
{
    b[L] += c;
    b[R + 1] -= c;
}

int main()
{
    int n, m;
    cin >> n >> m;
    for(int i = 1; i <= n; ++ i)
    {
        cin >> a[i];
        insert(i, i, a[i]);
    }
    while(m --)
    {
        int L, R, c;
        cin >> L >> R >> c;
        insert(L, R, c);
    }
    for(int i = 1; i <= n; ++ i)
    {
        b[i] += b[i-1];
        cout << b[i] << " ";
    }
}
上一篇:白书-多重部分和问题


下一篇:牛客小白月赛17 G 区间求和