浙大 PAT 甲级 1103 Integer Factorization DFS+剪枝
作者:互联网
这题的超时弄得我要崩溃了…各种细节处的剪枝,不停剪了很多地方,依然超时。最后用整型数组代替了vector,通过。血泪教训,第二次了,超时的时候把vector换成原生数组会快好几倍。
#include<stdio.h>
#include<vector>
#include<math.h>
#include<memory.h>
using namespace std;
vector<int> addend;
int bestans[405];
int bestmax;
int bestsum;
int N, K, P;
void DFS(int res, int* ans, int sum, int start,int layer)
{
if (layer >= K) return;
for (int i = start; i >= 0; i--)
{
res += addend[i];
if (res <= N)
{
ans[layer] = i + 1;
layer++;
sum += (i + 1);
if (layer == K && res == N)
{
if (sum > bestsum || (sum == bestsum&&ans[0] > bestans[0]))
{
bestsum = sum;
memcpy(bestans, ans, sizeof(int)*K);
}
break;
}
else if (layer < K && res < N)
{
DFS(res, ans, sum, i,layer);
}
layer--;
sum -= (i + 1);
}
res -= addend[i];
}
}
void init()
{
for (int i = 1; i <= N; i++)
{
int add = pow((double)i, P);
if (add > N) break;
else addend.push_back(add);
}
}
int main()
{
scanf("%d %d %d", &N, &K, &P);
bestsum = -1;
init();
int ans[405];
DFS(0, ans, 0, addend.size() - 1, 0);
if (bestsum == -1)
{
printf("Impossible\n");
}
else
{
printf("%d = ", N);
for (int i = 0; i < K; i++)
{
if (i == K - 1)
{
printf("%d^%d\n", bestans[i], P);
}
else
{
printf("%d^%d + ", bestans[i], P);
}
}
}
return 0;
}
标签:剪枝,layer,PAT,addend,int,res,bestsum,Factorization,ans 来源: https://blog.csdn.net/qq_39115541/article/details/100518232