Skip to content

Commit c3c0d42

Browse files
Create solution002.cpp
1 parent 12f6911 commit c3c0d42

1 file changed

Lines changed: 87 additions & 0 deletions

File tree

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
/*
2+
Problem:
3+
You are given an array of n positive integers and an integer k (k >= 2).
4+
Count the number of unordered pairs (i, j) such that ai * aj is a perfect k-th power.
5+
6+
Approach:
7+
1. Precompute smallest prime factor (SPF) up to max(ai).
8+
2. For each number, compute its prime factorization.
9+
3. Reduce exponents modulo k to form a "signature".
10+
4. Compute the complementary signature needed to make exponents divisible by k.
11+
5. Use a map to count matching signatures seen so far.
12+
13+
Time Complexity: O(n log A)
14+
Space Complexity: O(n)
15+
16+
Problem Link:
17+
https://codeforces.com/problemset/problem/1225/D
18+
*/
19+
20+
#include <bits/stdc++.h>
21+
using namespace std;
22+
23+
static const int MAXA = 100000;
24+
25+
int main() {
26+
ios::sync_with_stdio(false);
27+
cin.tie(nullptr);
28+
29+
int n, k;
30+
cin >> n >> k;
31+
32+
vector<int> a(n);
33+
for (int i = 0; i < n; i++) {
34+
cin >> a[i];
35+
}
36+
37+
// Step 1: Compute Smallest Prime Factor (SPF)
38+
vector<int> spf(MAXA + 1);
39+
for (int i = 1; i <= MAXA; i++) spf[i] = i;
40+
41+
for (int i = 2; i * i <= MAXA; i++) {
42+
if (spf[i] == i) {
43+
for (int j = i * i; j <= MAXA; j += i) {
44+
if (spf[j] == j)
45+
spf[j] = i;
46+
}
47+
}
48+
}
49+
50+
// Map to store frequency of signatures
51+
map<vector<pair<int,int>>, long long> freq;
52+
long long answer = 0;
53+
54+
// Step 2–5: Process each number
55+
for (int x : a) {
56+
map<int,int> factorCount;
57+
58+
// Factorize using SPF
59+
while (x > 1) {
60+
int p = spf[x];
61+
factorCount[p]++;
62+
x /= p;
63+
}
64+
65+
vector<pair<int,int>> signature;
66+
vector<pair<int,int>> complement;
67+
68+
for (auto &it : factorCount) {
69+
int prime = it.first;
70+
int exp = it.second % k;
71+
72+
if (exp != 0) {
73+
signature.push_back({prime, exp});
74+
complement.push_back({prime, (k - exp) % k});
75+
}
76+
}
77+
78+
// Count valid pairs
79+
answer += freq[complement];
80+
81+
// Store current signature
82+
freq[signature]++;
83+
}
84+
85+
cout << answer << "\n";
86+
return 0;
87+
}

0 commit comments

Comments
 (0)