[Code source daily question Div1] Picking peaches "prefix sum + map count"

picking peaches

Title description:

Give you nan array of length , give you, ask how many subintervals exist that satisfy(a[l]+a[l+1]+...+a[r]) % k = r - l + 1

Ideas:

If we do a prefix sum, the formula becomes(sum[r]-sum[l-1]) % k = r-l+1

It doesn't make sense to do that.

You can use an idea in high school mathematics to put the same variables together

sum[r] - r - (sum[l-1] - (l - 1)) % k = 0

can be sum[i]-iseen as a whole

To sum[i]-ifind the difference,sum[i]-i - (sum[i-1] - (i-1)) = sum[i]-sum[i-1] - 1 = ar[i]-1

So we can consider letting br[i] = ar[i]-1, and then find a prefix sum preto get the requirement just now

So now the problem is transformed into, find such [l,r]that in the sense of modulo k pre[r]=pre[l-1], and the length is less than or equal tok

We can use map to count and use double pointers to maintain the interval length less than or equal tok

#include <bits/stdc++.h>
using namespace std;

#define endl '\n'
#define inf 0x3f3f3f3f
#define mod7 1000000007
#define mod9 998244353
#define m_p(a,b) make_pair(a, b)
#define mem(a,b) memset((a),(b),sizeof(a))
#define io ios::sync_with_stdio(false),cin.tie(0),cout.tie(0)
typedef long long ll;
typedef pair <int,int> pii;

#define MAX 300000 + 50
int n, m, k, x;
int tr[MAX];

void work(){
    
    
    cin >> n >> k;
    for(int i = 1; i <= n; ++i){
    
    
        cin >> tr[i];--tr[i];
        (tr[i] += tr[i - 1]);
        tr[i]%=k;
    }
    int l = 0;
    map<int, int>mp;
    ll ans = 0;
    for(int i = 0; i <= n; ++i){
    
    
        if(i - l + 1 > k)--mp[tr[l++]];
        ans += mp[tr[i]];
        ++mp[tr[i]];
    }
    cout << ans << endl;
}


int main(){
    
    
    io;
    work();
    return 0;
}

Guess you like

Origin blog.csdn.net/weixin_51216553/article/details/127780510