1103 Integer Factorization (30)(30 分)
The K-P factorization of a positive integer N is to write N as the sum of the P-th power of K positive integers. You are supposed to write a program to find the K-P factorization of N for any positive integers N, K and P.
Input Specification:
Each input file contains one test case which gives in a line the three positive integers N (<=400), K (<=N) and P (1<P<=7). The numbers in a line are separated by a space.
Output Specification:
For each case, if the solution exists, output in the format:
N = n~1~\^P + ... n~K~\^P
where n~i~ (i=1, ... K) is the i-th factor. All the factors must be printed in non-increasing order.
Note: the solution may not be unique. For example, the 5-2 factorization of 169 has 9 solutions, such as 12^2^ + 4^2^ + 2^2^ + 2^2^ + 1^2^, or 11^2^ + 6^2^ + 2^2^ + 2^2^ + 2^2^, or more. You must output the one with the maximum sum of the factors. If there is a tie, the largest factor sequence must be chosen -- sequence { a~1~, a~2~, ... a~K~ } is said to be larger than { b~1~, b~2~, ... b~K~ } if there exists 1<=L<=K such that a~i~=b~i~ for i<L and a~L~>b~L~
If there is no solution, simple output "Impossible".
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
题意比较好懂,容易想到dfs,但是不能纯回溯,需要剪枝,或者说按照一个非递减的顺序去试每个值,而且判断结果时满足k项就更新,因为从第一层开始,往下dfs,每一层的初始试验值都大于等于上一层的正在试验值,如果遇到跟之前一次结果相同的,序列一定比之前大。
代码:
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
using namespace std;
int n,k,p;
vector<int> temp,ans;
int pow_[];///把可能用到的p次方都算出来,要多算一个 这样循环结束 不至于死循环(如果算的pow_[j] 都小于n 那么最大的max(j) + 1对应pow_[j]初始为0
int pow(int t) {
int d = ;
for(int i = ;i < p;i ++) {
d *= t;
}
return d;
}
void dfs(int t,int s,int last) {///last是上一层正在尝试的 ,本次从last开始 达到非递减的目的
if(t >= k) {
if(!s) {
ans = temp;
}
return;
}
while(pow_[last] <= s) {///这里防止死循环 如果last = max(j) 保证pow_[last]能使循环结束
temp.push_back(last);
dfs(t + ,s - pow_[last],last);
temp.pop_back();
last ++;
}
}
int main() {
scanf("%d%d%d",&n,&k,&p);
int j = ,d = ;
while(d <= n) {
pow_[j ++] = d;
d = pow(j);
}
pow_[j] = d;///多算一次 不然判断会死循环
dfs(,n,);
if(ans.empty())printf("Impossible");
else {
printf("%d = %d^%d",n,ans[k - ],p);
for(int i = k - ;i >= ;i --) {
printf(" + %d^%d",ans[i],p);
}
}
}
最新文章
- iOS多线程GCD
- HUST1024 dance party(最大流)
- 安装VMware-tools的问题
- 解决fonts.gstatic.com无法访问
- Ubuntu 12.04本地编译安装Vim
- (原+转)C++中的lambda表达式
- MSSQL 当前会话设置隔离级别与查询
- MVC创建
- 新鲜出炉的JSON,拿走不谢!
- 【Unity游戏开发】Lua中的os.date和os.time函数
- 基于 HTML5 结合工业互联网的智能飞机控制
- KEIL打开的工程所在目录过深将会编译出错
- Select模式和超时
- 安装PostGIS 2.1.1 时遇到checking for library containing GDALAllRegister... no
- Laravel 的 Events(事件) 及 Observers(观察者)
- 【WPF】ScrollViewer无法滚动的问题
- Spring jndi数据源配置方法
- [WebKit] JavaScriptCore解析--基础篇 (一)JSC与WebCore
- (解释文)My SQL中主键为0和主键自排约束的关系
- sql server动态行列转换