S SmartDocs
Serie: Algorithms cpp 42 líneas · Actualizado 2026-04-05

greedy_v2.cpp

Algorithms/greedy_v2.cpp

// Greedy V2 Algorithm


#include <iostream>
#include <map>
using namespace std;

int main() {

    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);

    int T;
    cin >> T;

    while (T--) {
        int n;
        cin >> n;
        
        // use map to count the freq of b[k] = a[k] - k
        map<int, long long> cnt;

        for (int k = 1; k <= n; k++) {
            int a;
            cin >> a;
            cnt[a - k]++;   // count the freq of b[k] = a[k] - k
        }
        
        // for each b[k], count the number of pairs C(c, 2) = c * (c - 1) / 2
        long long ans = 0;
        map<int, long long>::iterator it;
        for (it = cnt.begin(); it != cnt.end(); it++) {
            long long c = it->second;
            ans += c * (c - 1) / 2;
        }

        cout << ans << endl;
    }

    return 0;
}

Artículos relacionados