POJ 3421 X-factor Chains(构造)

这条链依次乘一个因子。因为n<2^20,sqrt(n)分解因子,相同的因子相对顺序取一个。

组合公式计算一下就好。

#include<cstdio>
#include<iostream>
#include<string>
#include<cstring>
#include<queue>
#include<vector>
#include<stack>
#include<vector>
#include<map>
#include<set>
#include<algorithm>
#include<cmath>
//#include<bits/stdc++.h>
using namespace std;

typedef long long ll;
#define PB push_back

const int maxn = 1<<20;

ll fac[21];
void calFac(int n = 20)
{
    fac[0] = 1;
    for(int i = 1; i <= n; i++){
        fac[i] = fac[i-1]*i;
    }
}

int primeDecompose(int n,ll &div)
{
    int re = 0; div = 1;

    for (int i = 2; i*i <= n; i++){
        int cnt = 0;
        while (n % i == 0){
            n /= i;
            cnt++;
            re++;
        }
        if(cnt) div *= fac[cnt];
    }
    if(n>1) re++;
    return re;
}

//#define LOCAL
int main()
{
#ifdef LOCAL
    freopen("in.txt","r",stdin);
#endif
    calFac();
    int X;
    while(~scanf("%d",&X)){
        ll div;
        int len = primeDecompose(X,div);
        ll shc = fac[len]/div;
        printf("%d %I64d\n",len,shc);
    }
    return 0;
}

我尝试用预先筛sqrt(n)以内的素数来加速判断,结果却慢了26ms..

#include<cstdio>
#include<iostream>
#include<string>
#include<cstring>
#include<queue>
#include<vector>
#include<stack>
#include<vector>
#include<map>
#include<set>
#include<algorithm>
#include<cmath>
//#include<bits/stdc++.h>
using namespace std;

typedef long long ll;
#define PB push_back

const int maxn = 1<<20;
const int sqrn = 1<<10;//(int)sqrt(maxn+0.5); + 5
const int PrmSz = (1<<8)+5; // (sqrn>>2) + 5

bool isNot[sqrn];
int Prm[PrmSz], tot;

void seive(int n = sqrn) //sqrt(sqrt(maxn))
{
    int m = sqrt(n+0.5);
    isNot[0] = isNot[1] = true;
    for(int i = 2; i <= m; i++){
        if(!isNot[i])
        for(int j = i*i; j <= n; j += i){
            isNot[j] = true;
        }
    }
    for(int i = 2; i <= n; i++){
        if(!isNot[i]) //Prm.PB(i);
            Prm[tot++] = i;
    }
}

ll fac[21];
void calFac(int n = 20)
{
    fac[0] = 1;
    for(int i = 1; i <= n; i++){
        fac[i] = fac[i-1]*i;
    }
}

inline int primeDecompose(int n,ll &div)
{
    int re = 0; div = 1;
    for (int i = 0; i < tot && Prm[i] <= n; i++){
        int p = Prm[i], cnt = 0;
        while (n % p == 0){
            n /= p;
            cnt++;
            re++;
        }
        if(cnt) div *= fac[cnt];
    }
    if(n>1) re++;
    return re;
}

//#define LOCAL
int main()
{
#ifdef LOCAL
    freopen("in.txt","r",stdin);
#endif
    seive();
    calFac();
    int X;
    while(~scanf("%d",&X)){
        ll div;
        int len = primeDecompose(X,div);
        ll shc = fac[len]/div;
        printf("%d %I64d\n",len,shc);
    }
    return 0;
}

 

posted @ 2015-10-20 21:54  陈瑞宇  阅读(236)  评论(0编辑  收藏  举报