CodeForces - 1247D Power Products【數論】

題目鏈接:https://codeforces.com/problemset/problem/1247/D

題意:給你一個序列a,問有多少對i,j滿足存在x使得 ai * aj = x ^ k , k是給定的。

思路:兩個數滿足條件就是要相同因數的個數要是k的倍數,
把每個數質因數分解,然後算出來補數,例如還需要2個2,就是4
然後我們就在map裏找這個補數,然後再將當前數的貢獻存入map

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define ls rt << 1
#define rs rt << 1|1
#define mid ((l + r) >> 1)
#define lson l, mid, ls
#define rson mid + 1, r, rs
const int maxn = 1e5 + 10;
int aa[maxn], prime[maxn], a[maxn];
map<ll, int> mp;
int tot = 0;
void init()
{
    for(int i = 2; i < maxn; ++i)
    {
        if(!aa[i])
        {
            prime[++tot] = i;
            for(int j = i * 2; j < maxn; j += i)
                aa[j] = 1;
        }
    }
}

int main()
{
    init();
    int n, k;
    scanf("%d%d", &n, &k);
    for(int i = 1; i <= n; ++i) scanf("%d", &a[i]);
    ll ans = 0;
    for(int i = 1; i <= n; ++i)
    {
        queue<pair<int, int> > q;
        while(!q.empty()) q.pop();
        int x = a[i];
        if(x == 1) q.push({1, 1});
        for(int j = 1; j <= tot && prime[j] <= x; ++j) //質因數分解
        {
            int cnt = 0;
            while(x % prime[j] == 0)
            {
                x /= prime[j];
                ++cnt;
            }
            cnt = cnt % k;
            if(cnt) q.push({prime[j], cnt});
        }
        bool flag = true;
        ll res = 1, res1 = 1;
        while(!q.empty())
        {
            pair<int, int> tmp = q.front(); q.pop();
            for(int j = 1; j <= k - tmp.second; ++j) //算補數
                res = res * tmp.first;
            for(int j = 1; j <= tmp.second; ++j) //算貢獻
                res1 = res1 * tmp.first;
        }
        if(res > 100000) flag = false; //可以優化一下,超出值的範圍一定不行
        if(flag) ans += mp[res];
        mp[res1]++;
    }
    printf("%lld\n", ans);
    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章