1103 Integer Factorization(DFS)

大意:将整数N分成K个正整数的P次幂之和。 N (≤400), K (≤N) and P (1<P≤7).

  • 想到dfs的树形结构,并以想到现场的还原
  • 要求字典序大,倒序从大的开始选择即可
#include<bits/stdc++.h>
#define f(i,a,b) for(int i=a;i<=b;++i)
#define fd(i,a,b) for(int i=a;i>=b;--i)
using namespace std;
const int N = 1e5 + 50;
int n, k, p;
vector<int> fac;//可选物品
vector<int> res;//答案序列,要求字典序大?,先选大的
vector<int> stk;//dfs答案栈
int power(int x) {
	int res = 1;
	f(i, 1, p)res = res * x;
	return res;
}
void getfac() {
	int id = 1,x=id;
	while ( x<= n) {
		fac.emplace_back(x);
		x = power(++id);
	}
}
int resw = 0;
void dfs(int idx, int v, int num, int w) {
	if (idx < 0)return;
	if (v == n && num == k) {
		if (w > resw) {
			resw = w;
			res = stk;
		}
	}
	if (v > n || num > k)return;//走下去已经没有意义
	stk.emplace_back(idx+1);
	dfs(idx, v + fac[idx], num + 1, w + idx + 1);
	stk.pop_back();
	dfs(idx - 1, v, num, w);
}
int main()
{
#ifndef ONLINE_JUDGE
	freopen("in.txt", "r", stdin);
#endif
	cin >> n >> k >> p;
	getfac();
	dfs(fac.size() - 1, 0, 0,0);
	if (resw) {
		//169 = 6^2 + 6^2 + 6^2 + 6^2 + 5^2
		cout << n << " = ";
		int fg = 0;
		for (auto i : res) {
			if (fg)cout << " + " << i << "^" << p;
			else fg++, cout << i << "^" << p;
		}
		cout << endl;
	}
	else puts("Impossible");
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值