Cod sursa(job #3292186)

Utilizator BledeaAlexBledea Alexandru BledeaAlex Data 7 aprilie 2025 12:11:36
Problema Pairs Scor 0
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.66 kb
#include <bits/stdc++.h>

using namespace std;

const long long M_MAX = 1e6 + 5, MAX_PRIME = 1e3 + 10;

void SetInput(string name)
{
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);

    (void)!freopen((name + ".in").c_str(), "r", stdin);
    (void)!freopen((name + ".out").c_str(), "w", stdout);
}

int fr[M_MAX];
bool sieve[M_MAX];
int group[M_MAX];
bool isSquareFree[M_MAX];
int primeCnt[M_MAX];

void PrecalcGroupes()
{
    sieve[0] = sieve[1] = 1;
    for(int i = 2; i < M_MAX; i++)
        group[i] = 1;

    for(int i = 2; i < M_MAX; i++)
    {
        if(sieve[i] == 0)
        {
            for(int j = i; j < M_MAX; j += i)
            {
                sieve[j] = 1;
                primeCnt[j]++;
                group[j] *= i;
            }
            sieve[i] = 0;
        }

        if(group[i] == i)
            isSquareFree[i] = true;
    }
}

inline long long Comb2(const int& n)
{
    return 1LL * n * (n - 1) / 2;
}

void Solve()
{
    int N, M = 0;
    cin >> N;

    for(int i = 1, x; i <= N; i++)
    {
        cin >> x;
        M = max(M, x);
        fr[x] = 1;
    }

    long long sol = Comb2(N);

    for(int i = 2; i <= M; i++)
        if(isSquareFree[i])
        {
            int multiples = 0;

            for(int j = i; j <= M; j += i)
                multiples += fr[j];

            long long pairs = Comb2(multiples);

            if(primeCnt[i] == 1)
                sol -= pairs;
            else
                sol += pairs;
        }

    cout << sol << '\n';
}

int main()
{
    SetInput("pairs");

    PrecalcGroupes();
    Solve();

    return 0;
}