PAT (Advanced Level) 1103 Integer Factorization——暴搜剪枝+KSM

题目传送门

类似数字分解的暴搜
枚举第t个数字时,取值不小于第t-1个数字
取值的最大值x:若第t个数字为x+1,剩下的k-t位都为1,累加结果会超过n
加上了快速幂的代码复习一下
暴搜的模板不要写错啊喂QwQ

# 暴力搜索长度位n的序列解
dfs (int t, ...) {
    if (t > n) {
       # 记录答案
       return;
    }
    for (第t位的所有可能取值) {
        # 记录第t位的取值
        dfs(t+1, ...);
        # 清除第t位的取值
    }
}
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
using namespace std;

int n, k, p;

int KSM(int a, int p)
{
	if (a == 0) return 0;
	if (a == 1) return 1;
	if (p == 0) return 1;
	int ans = a;
	p--;
	while (p)
	{
		if (p & 1) ans = ans * a;
		p >>= 1;
		a = a * a;
	}
	return ans;
}

int ans[500];
int ans_tot = 0;
int num[500];
int flag = 0;

int judge() {
	for (int i = 1; i <= k; ++i)
		if (num[i] > ans[i]) return 1;
		else if (num[i] < ans[i]) return 0;
	return 0;
}

void dfs(int res,int t,int tot) {
	if (t > k) {
		if (res == 0) {
			flag = 1;
			if (tot > ans_tot) {
				ans_tot = tot;
				for (int i = 1; i <= k; ++i)
					ans[i] = num[i];
			}
			else if (tot == ans_tot) {
				if (judge()) {
					for (int i = 1; i <= k; ++i)
						ans[i] = num[i];
				}
			}
		}
		return;
	}
	for (int i = num[t - 1];; ++i) {
		int _ = KSM(i, p);
		if (_ + k - t > res) break;
		num[t] = i;
		dfs(res - _, t + 1, tot + i);
		num[t] = 0;
	}
}

int main()
{
	scanf("%d%d%d", &n, &k, &p);
	num[0] = 1;
	dfs(n, 1, 0);
	if (!flag) {
		printf("Impossible");
		return 0;
	}
	printf("%d =", n);
	for (int i = k; i >= 1; i--) {
		printf(" %d^%d", ans[i], p);
		if (i > 1) printf(" +");
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值