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这一参数。