Source Code
#include<bits/stdc++.h>
#include<cstdlib>
#define ll long long
#define ln length()
#define sz size()
#define ff first
#define ss second
#define pq priority_queue<ll,vector<ll>,greater<ll>>
#define all(v) v.begin(),v.end()
#define FS ios_base::sync_with_stdio(0),cin.tie(0),cout.tie(0);
#define ul unsigned long long
#define tc ll tt; cin>>tt; while(tt--)
#define ld long double
#define ln length()
#define el "\n"
#define ts(c) to_string(c)

using namespace std;

int main()
{
    FS
    tc {
        ll n,k;
        cin>>n>>k;
        vector<ll>v(n);
        ll pre[n+1],suf[n+1];
        map<ll,vector<ll>>mpp,mps;
        for (int i=0;i<n;i++) cin>>v[i];
        pre[0] = v[0],suf[n] = 0;
        for (int i=1;i<=n;i++){
            pre[i] = pre[i-1] + v[i];
            suf[n-i] = suf[n-i+1] + v[n-i];
            mps[suf[n-i] % k].push_back(n-i);
            sort(all(mps[suf[n-i]%k]));
        }
        //for (int i=0;i<n;i++) cout<<pre[i]<<' '<<suf[i]<<el;
        ll res = 0;
        for (int i=0;i<n;i++){
            int f = k - (pre[i]%k);
            if (pre[i]%k==0) f = 0;
            int r = upper_bound(all(mps[f]),i) - mps[f].begin();
            if (r>=0 && r<mps[f].sz){
                res += (mps[f].sz - r);
            }

        }
        cout<<res<<el;
    }
}
Copy
Number of Ways heba.daraghmeh
GNU G++17
2064 ms
792 KB
Time Limit Exceeded