Source Code
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;

int main()
{

    ios_base::sync_with_stdio(0);
    cout.tie(0); cout.tie(0);

    int tt;
    cin >> tt;
    while(tt--){

        ll n , k;
        cin >> n >> k;
        vector<ll> a(n);

        for(ll &x : a){
            cin >> x;
        }

        map<ll ,ll> cnt;
        ll sum = 0;
        for(int i = n - 1; ~i ; i--){
            sum += a[i];
            cnt[sum % k] += 1;
        }
        ll ans = 0;
        ll prefix = 0 ,suffix = sum;
        for(int i = 0 ; i < n ; i++){
            cnt[suffix % k] -= 1;
            suffix -= a[i];
            prefix += a[i];
            ans += cnt[k - (prefix % k == 0 ? k : prefix % k)];
        }
        cout << ans << '\n';
    }
    return 0;
}
Copy
Number of Ways Greedious
GNU G++17
763 ms
26.8 MB
Accepted