range update on array

1k views Asked by At

You have n length array having all elements 0 initially. You have to execute 2-types of m commands.

type 1: l r (l ≤ l ≤ r ≤ n) — Increase all elements of the array by one, whose indices belong to the range [l, r].

type 2: l r (1 ≤ l ≤ r ≤ m) — Execute all the commands whose indices are in the range [l, r]. It's guaranteed that r is strictly less than the
enumeration/number of the current command.

Input:

The first line contains integers n and m. Next m lines contain commands in the format, described in the statement: t, l, r, where t - the number of types (1 or 2).

Output:

print an array a, after executing every command. The numbers have to be separated by spaces. As the numbers can be quite large, print them modulo 109 + 7.

Constraints:

1 ≤ n, m ≤ 105
1

There are 1 answers

0
kumar-kunal On BEST ANSWER

This is codechef problem,you can see editorial here and here is my source code

#include<bits/stdc++.h>
#define mp(x,y) make_pair((x),(y))
#define ll long long int
#define mem(x,y) memset(x,y,sizeof(x))
#define pb push_back
#define MOD (ll)(1e9+7)
#define X first
#define all(a) a.begin(),a.end()
#define Y second
#define f(i,a,b) for(int i=a;i<b;i++)
using namespace std;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
typedef vector<int> vi;
typedef vector<ll> vll;
typedef vector<pii> vpii;
typedef vector<pll> vpll;

struct query{
    int type,l,r;
};
query q[100005];
int main(){
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    int t;
    cin>>t;
    while(t--){
        int n,m;
        cin>>n>>m;
        vll a(n+1,0),c(m+1,0);
        ll sum=0;
        for(int i=1;i<=m;i++){
            cin>>q[i].type>>q[i].l>>q[i].r;
        }
        for(int i=m;i>=1;i--){
          //  f(i,1,m+1)cout<<c[i]<<" ";cout<<"\n";
            c[i-1]+=c[i];
            c[i-1] = (c[i-1]+MOD)%MOD;
            if(q[i].type==2){
                c[q[i].r]+=c[i]+1;
                c[q[i].r] = (c[q[i].r]+MOD)%MOD;
                c[q[i].l-1]-=c[i]+1;
                c[q[i].l-1] = (c[q[i].l-1]+MOD)%MOD;
            }
        }
        for(int i=1;i<=m;i++){
            if(q[i].type==1){
                a[q[i].r]+=c[i]+1;
                a[q[i].r] = (a[q[i].r]+MOD)%MOD;
                a[q[i].l-1]-=(c[i]+1);
                a[q[i].l-1] = (a[q[i].l-1]+MOD)%MOD;
            }
        }
        for(int i=n-1;i>=1;i--){
            a[i] = a[i+1]+a[i];
            a[i] = (a[i]+MOD)%MOD;
        }
        f(i,1,n+1)cout<<a[i]<<" ";
        cout<<"\n";
    }
    return 0;
}