1. 程式人生 > >ACM-ICPC 2018 南京賽區網路預賽 J.Sum [ 類打表 ]

ACM-ICPC 2018 南京賽區網路預賽 J.Sum [ 類打表 ]

A square-free integer is an integer which is indivisible by any square number except 11. For example, 6 = 2 \cdot 36=2⋅3 is square-free, but 12 = 2

2 3 is not, because 2 2
is a square number. Some integers could be decomposed into product of two square-free integers, there may be more than one decomposition ways. For example,
6 = 1 6 = 6
1 = 2 3 = 3 2 , n = a b , n = b a
, are considered different if a b . f(n) is the number of decomposition ways that n=ab such that a and b are square-free integers. The problem is calculating i = 1 n f ( i )

Input
The first line contains an integer T(T≤20), denoting the number of test cases.
For each test case, there first line has a integer n ( n 2 10 7 )

Output
For each test case, print the answer i = 1 n f ( i )

Hint
i = 1 8 f ( i ) = f ( 1 ) + + f ( 8 ) =1+2+2+1+2+4+2+0=14=1+2+2+1+2+4+2+0=14.

題意:找出一個數的所有乘數組合,使這些乘數組合中的任一因數都不存在完全平方因數。求從1到n的的所有數的乘數組合之和。

思路:
打個表找到每一個數的最小的質因數 ,然後
if ( i % (mprim[i] * mprim[i] * mprim[i]) == 0 ) ans[i] = 0;
else if ( i % (mprim[i] * mprim[i]) == 0 ) ans[i] = ans[i / (mprim[i]*mprim[i])];
else ans[i] = ans[i / mprim[i]] * 2;

AC code:

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>

using namespace std;

typedef long long ll;
typedef pair<int,int>pii;

const int maxn = 2e7+50;

int p[maxn] ,mprim[maxn] ,tot ;
bool vis[maxn];
ll ans[maxn];

void init() {
    tot = 0;
    memset(vis ,true ,sizeof(vis) );
    for (int i = 2;i < maxn;i++) {
        if ( vis[i] ) p[tot++] = i,mprim[i] = i;
        for (int j = 0; j < tot && i * p[j]< maxn ;j++) {
            vis[i * p[j]] = false;
            mprim[i * p[j]] = p[j];
            if ( i % p[j] == 0 ) break;
        }
    }
    ans[1] = 1;
    for (int i = 2;i < maxn ;i++) {
        if ( i % (mprim[i] * mprim[i] * mprim[i]) == 0 ) ans[i] = 0;
        else if ( i % (mprim[i] * mprim[i]) == 0 ) ans[i] = ans[i / (mprim[i]*mprim[i])];
        else ans[i] = ans[i / mprim[i]] * 2;
    }
}

int main() {
    init();
    int t ,n ; cin>>t;
    for (int i = 1;i <= t;i++) {
        scanf("%d",&n);
        ll res = 0;
        for (int i = 1;i<=n;i++) res += ans[i];
        printf("%lld\n",res);
    }
    return 0;
}