1. 程式人生 > 其它 >字首和差分(一維和二維)

字首和差分(一維和二維)

一維字首和

例題

#include<iostream>
using namespace std;
const int N = 1e5+10;
int n,m;
int s[N],num[N];
int main()
{
    cin >> n >> m;
    for(int i = 1; i <= n; i ++ )
    {
        cin >> num[i];
        s[i] = s[i - 1] + num[i];
    }
    while(m -- )
    {
        int l,r;
        cin >> l >> r;
        cout << s[r] - s[l - 1] << endl;
    }
    return 0;
}

二維字首和

例題

#include<iostream>
using namespace std;
const int N = 1e3+10;
int mat[N][N],s[N][N];
int n,m,q;
int main()
{
    cin >> n >> m >> q;
    for(int i = 1; i <= n; i ++ )
        for(int j = 1; j <= m; j ++ )
            cin >> mat[i][j];
    for(int i = 1; i <= n; i ++ )
        for(int j = 1; j <= m; j ++ )
            s[i][j] = s[i - 1][j] + s[i][j - 1] - s[i - 1][j - 1] + mat[i][j];
    while(q -- )
    {
        int x1,y1,x2,y2;
        cin >> x1 >> y1 >> x2 >> y2;
        cout << s[x2][y2] - s[x1 - 1][y2] - s[x2][y1 - 1] + s[x1 - 1][y1 - 1] << endl;
    }
    return 0;
}

一維差分

例題

#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 1e5+10;
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];
    for (int i = 1; i <=n; 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 <cstring>
#include <algorithm>
using namespace std;
const int N = 1e3+10;
int a[N][N],b[N][N];
void insert(int x1,int y1,int x2,int y2,int c)
{
    b[x1][y1]+=c;
    b[x1][y2+1]-=c;
    b[x2+1][y1]-=c;
    b[x2+1][y2+1]+=c;
}
int main()
{
    int n,m,q;
    cin >> n >> m >> q;
    for (int i = 1; i <= n; i ++ )
        for (int j = 1; j <= m; j ++ )
        {
            cin >> a[i][j];
            insert(i,j,i,j,a[i][j]);
        }
    while (q -- )
    {
        int x1,y1,x2,y2,c;
        cin >> x1 >> y1 >> x2 >> y2 >> c;
        insert(x1,y1,x2,y2,c);
    }
    for (int i = 1; i <= n; i ++ )
        for(int j = 1; j <= m; j ++)
            b[i][j]+=b[i-1][j]+b[i][j-1]-b[i-1][j-1];
    for (int i = 1; i <= n; i ++ )
    {
        for(int j = 1; j <= m; j ++)
        cout << b[i][j] << ' ';
        cout << endl;
    }
}