Cod sursa(job #1243762)

Utilizator MarcvsHdrMihai Leonte MarcvsHdr Data 16 octombrie 2014 13:09:07
Problema Pairs Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.71 kb
#include <iostream>
#include <fstream>

#include <vector>

#define MAXN 1000001

int unique_div[MAXN];
bool in_input[MAXN];
bool prime[MAXN];
bool basecomp[MAXN];

int main()
{
  std::ifstream in("pairs.in");
  std::ofstream out("pairs.out");

  int n;
  int max = 0;
  in >> n;
  std::vector<int> v;
  for (int i = 0; i < n; ++i) {
    int x;
    in >> x;
    v.push_back(x);
    in_input[x] = true;
    max = (max < x ? x : max);
  }

  // Assume all numbers are basecomp.
  for (int i = 1; i <= max; ++i) {
    basecomp[i] = true;
  }

  // Look how many unique prime divisors every number has.
  for (int i = 2; i <= 1000; ++i) {
    if (unique_div[i] == 0) {
      unique_div[i]++;

      for (int j = 2; j * i <= max; ++j) {
        unique_div[i * j]++;
        if (j % i == 0) {
          basecomp[i * j] = false;
        }
      }
    }
  }

  unsigned long long invalid = 0;
  for (int i = 2; i <= 1000; ++i) {
    if (basecomp[i]) {
      int count = 0;
      for (int j = 1; j * i <= max; ++j) {
        // For basic composition numbers, see how many times they occur.
        if (in_input[i * j]) {
          count++;
        }
      }

      // This many pairs are invalid based on sharing unique_div[i] primes.
      if (unique_div[i] % 2 == 1) {
        invalid += ((unsigned long long)count - 1) * count / 2;
      } else {
        invalid -= ((unsigned long long)count - 1) * count / 2;
      }
    }
  }

  // All numbers between 1000 and 1000000 which don't already have a divisor are
  // prime (and thus, basecomp, and can only occur in the input in their basic
  // form, so they don't produce any invalid pairs).
  unsigned long long sol = ((unsigned long long)n - 1) * n / 2 - invalid;

  out << sol << std::endl;

  return 0;
}