dp——完全背包+大数存储+数论

题目:

Least common multiple

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. 

Input

There 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.

Output

Output 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.

题目链接:

https://vjudge.net/problem/HDU-3092

分析:

1、经分析,加数只能是互质的,而且加数本身一定是素数的幂。因此该问题转化为完全背包问题,由于每个加数只能是某一次幂(如果2是加数,则4,8,16,32等通通不能出现,不然就不是互质的了),所以滚动数组应该倒序扫描。

2、为了存储最小公倍数这个大数,又能用于不断地比较,我开了两个数组,一个是res[],存储最小公倍数的模数,一个是用于比较的double类型的dp[],dp[] = log10(res[]);

代码:

#include <bits/stdc++.h>
using namespace std;
const int maxn = 3010;
int s, mod;
int p[maxn];
vector<int> prime;
long long res[maxn];//save res % mod
double dp[maxn];///save log(res) which is used to compare the big data;

void chart()
{
	for (int i = 2; i <= maxn; i++)
		if (!p[i])
			for (int j = i * 2; j <= maxn; j += i)
				p[j] = 1;
	for (int i = 2; i <= maxn; i++)
		if (!p[i])
			prime.push_back(i);
	return;
}
int main()
{
	chart();
	while (cin >> s >> mod)
	{
		for (int i = 0; i < maxn; i++)
			dp[i] = 0.0, res[i] = 1;
		for(int k = 0; k < prime.size(); k++)
			for(int i = s; i >= prime[k]; i--)
				for(int j = prime[k]; i - j >= 0; j *= prime[k])
					if (dp[i - j] + log10(j) > dp[i])
					{
						dp[i] = dp[i - j] + log10(j);
						res[i] = res[i - j] * j % mod;
					}
		cout << res[s] << endl;
	}

	return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值