1103. Integer Factorization (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,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 = n1^P + … nK^P
where ni (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 { a1, a2, … aK } is said to be larger than { b1, b2, … bK } if there exists 1<=L<=K such that ai=bi for ibL
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
结题思路 :
题意要求我们找到可行最大的“棋盘距离”(P为不定值)。
要求1:将输入视作一个多维向量的绝对距离;
要求2:求取最大的棋盘距离;
要求3:在最大的棋盘距离的前提下找到根据定义的序列比较的最大值;
要求4:由于绝对距离部分<=400,所以直接爆搜即可。
程序步骤:
第一步、提前计算[1,20]的P次方;
第二步、由于要求我们输出序列比较重较大的,这里要求我们从大数开始寻找可行解即可。
第三步、根据棋盘距离确定最后的解,输出即可。
PS:开始以为并不需要第三步的内容也能得到最终解,但case2一直过不去。
后来自己想到了一个简单的case:
如下:
7=4+2+1
7=5+1+1
在遍历过程中先找到511,但后面会被421替换掉正确解。
具体程序(AC)如下:
#include <iostream>
#include <string>
#include <cstring>
#include <cmath>
#include <vector>
using namespace std;
vector<int> result;
vector<int> tmp;
int num[25];
int N,P,K;
int maxSum=0;
void printResult(vector<int>& result)
{
if(result.size()>0)
{
cout<<N<<" = "<<result[0]<<"^"<<P;
for(int i=1;i<K;++i)
cout<<" + "<<result[i]<<"^"<<P;
}
else
cout<<"Impossible";
cout<<endl;
}
void dsf(int sum,int deep,int max,int sSum)
{
//cout<<"deep: "<<deep<<endl;
if(deep==0)
{
if(sum==0)
{
if(sSum>maxSum)
{
result=tmp;
maxSum=sSum;
}
}
return ;
}
int i;
for(i=max;i>=1;--i)
{
if(sum-num[i]>=0)//这个正儿八经的剪枝,感觉不需要多说什么
{
tmp.push_back(i);
//cout<<"sum: "<<sum<<" deep: "<<deep<<" max: "<<i<<endl;
dsf(sum-num[i],deep-1,i,sSum+i);
tmp.pop_back();
}
}
return;
}
int main() {
// your code goes here
cin>>N>>K>>P;
int max;
max=(K>=2)?15:20;
result.clear();
tmp.clear();
num[0]=0;
for (int i = 1; i <= 20; ++i)
{
num[i] = 1;
for (int j = 0; j < P; ++j)
num[i] *= i;
}
dsf(N,K,max,0);
printResult(result);
return 0;
}