数论 + 完全背包

Partychen like to do mathematical problems. One day, when he was doing on a least common multiple(LCM) problem, he suddenly thought of a very interesting question: if given a number of S, and we divided S into some numbers , then what is the largest LCM of these numbers? partychen thought this problems for a long time but with no result, so he turned to you for help!
Since the answer can very big,you should give the answer modulo M.

InputThere are many groups of test case.On each test case only two integers S( 0 < S <= 3000) and M( 2<=M<=10000) as mentioned above.OutputOutput the largest LCM modulo M of given S.Sample Input
6 23
Sample Output
6


Hint: you can divied 6 as 1+2+3 and the LCM(1,2,3)=6 is the largest so we output 6%23=6.

题意:将一个数 n 分解成任意个数,这些数的和等于 n ,要求分解出来的这些数的 lcm 最大。
思路分析:首先被分解出来的数一定两两之间是互质的,因为如果存在一个数与其他的数不互质,那么这个数一定还可以再分成小一点的,确保其与其他的数均互质,同时也会增大lcm。
  这时只要找到小于 n 的所有质数,任意两个质数的 k 次幂均是互质的。这时就可以准变成为一个 完全背包,但是因为答案要对 mod 取余,而dp在转移的过程中又不能去取余,否则会出现错误,这时候可以采用对数,同时在新增一个辅助数组去取余即可。
代码示例:
ll n, m;
vector<ll>ve;
ll pt[3005];

void init(){
    for(ll i = 2; i <= 3000; i++){
        if (!pt[i]){
            ve.push_back(i);
            for(ll j = i+i; j <= 3000; j += i){
                pt[j] = 1;
            }
        }
    }  
}
double dp[3005];
ll ans[3005];

int main() {
    //freopen("in.txt", "r", stdin);
    //freopen("out.txt", "w", stdout);
    
    init();
    while(~scanf("%lld%lld", &n, &m)){    
        memset(dp, 0, sizeof(dp));
        for(ll i = 0; i <= n; i++) ans[i] = 1;
        
        for(ll i = 0; i < ve.size(); i++){
            for(ll j = n; j >= ve[i]; j--){
                ll num = 1;
                for(ll k = 1; k <= j/ve[i]; k++){
                    num *= ve[i];
                    if (j-num < 0) break;
                    //printf("***** %lf\n", log10(1.0*k*ve[i]));
                    if (dp[j] < dp[j-num]+log10(1.0*num)){
                        dp[j] = dp[j-num]+log10(1.0*num);
                        ans[j] = ans[j-num]*num%m;
                    }
                    //printf("+++ %lld %lld %lf \n", i, j, dp[j]);
                }         
            }
        }
        printf("%lld\n", ans[n]);
    }
    return 0;
}

 

转载于:https://www.cnblogs.com/ccut-ry/p/9147217.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值