1103 Integer Factorization (30 分)超时问题

1103 Integer Factorization (30 分)

在这里插入图片描述
Sample Input 1:
169 5 2
结尾无空行
Sample Output 1:
169 = 6^2 + 6^2 + 6^2 + 6^2 + 5^2
结尾无空行
Sample Input 2:
169 167 3
结尾无空行
Sample Output 2:
Impossible
结尾无空行

代码如下

#include<cstdio>
#include<algorithm>
#include<string>
#include<cstring>
#include<string.h>
#include<cmath>
#include<map>
#include<vector>
#include<queue>
#include<stack>
#include<set>
#include<iostream>


using namespace std;

const int max_n = 100006;
const int INF = (1 << 30);



vector<int> ans, temp,fac;

int maxFacSum = -1;

int n, k, p;



void dabiao()
{
	for (int i = 0; ; i++)
	{
		int a = (int)pow(i, p);
		fac.push_back(a);
		if (a > n)break;
	}
}

bool cmp(int a, int b)
{
	return a > b;
}
int cnt = 0;


void DFS(int nownum, int neednum, int cursum,int max)由于最后答案是非递增序列,所以每次m不能超过上一层递归的m(maxm)
{
	cnt++;
	if (neednum == 0)//找解
	{
		if (nownum == 0)//有解 存放在temp里
		{
			if (cursum >= maxFacSum)
			{
				maxFacSum = cursum;
				ans = temp;
			}
		}
		return;
	}
	for (int i = 1; i<=max; i++)
	{
		if (fac[i] > nownum)break;
		temp.push_back(i);
		DFS(nownum - fac[i], neednum - 1, cursum + i,i);
		temp.pop_back();
	}
}


int main()
{

	scanf("%d %d %d", &n, &k, &p);
	dabiao();
	DFS(n, k, 0,fac.size()-1);
	sort(ans.begin(), ans.end(), cmp);
	if (maxFacSum == -1)
	{
		printf("Impossible");
		return 0;
	}
	printf("%d = ", n);
	for (int i = 0; i < ans.size(); i++)
	{
		if (i)printf(" + ");
		printf("%d^%d", ans[i], p);
	}
	//cout << endl << cnt;
	return 0;
}

总结

我觉得这题对我收获非常大,一开始我只进行了部分剪枝:if (fac[i] > nownum)break; 但是剪了这一部分复杂度还是很高。后面看了别人的博客才知道,有这样的策略:由于答案是递减的,如果有一组解“6,6,6,6,5”,如果不剪枝,肯定在某一部中有如“6,6,6,5,6”, “6,6,5,6,6”之类重复的解,于是使下一次的枚举不要超过当前的值就好,即在DFS中加入max这一参数。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值