PAT1103.Integer Factorization

题目

The KP 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 KP 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:

1
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 122+42+22+22+12, or 112+62+22+22+22, 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,⋯,a**K } is said to be larger than { b1,b2,⋯,b**K } if there exists 1≤LK 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:

1
169 5 2

Sample Output 1:

1
169 = 6^2 + 6^2 + 6^2 + 6^2 + 5^2

Sample Input 2:

1
169 167 3

Sample Output 2:

1
Impossible

代码

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#include <iostream>
#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;

vector<int> factor;
vector<int> ans;
vector<int> tmp;
int N,K,P,fsum;


int pow(int t,int pow)
{
    int a=1;
    for(int i=0;i<pow;i++)
        a*=t;
    return a;
}


void DFS(int index,int nowK,int factSum,int powSum)
{
    //stop
    if(powSum>N) return;
    if(nowK==K)
    {
        if(powSum==N&&factSum>fsum)
        {
            fsum=factSum;
            ans=tmp;
        }
        return;
    }

    if(index>=1)
    {
        //select factor[index]
        tmp.push_back(index);
        DFS(index,nowK+1,factSum+index,powSum+factor[index]);


        tmp.pop_back();
        //not select factor[index]
        DFS(index-1,nowK,factSum,powSum);

    }

}
int main()
{

    scanf("%d%d%d",&N,&K,&P);

    int i,t;
    for(i=0;(t=pow(i,P))<=N;i++)
    {
        factor.push_back(t);
    }
    i--;
    DFS(i,0,0,0);

    if(fsum>0)
    {
        printf("%d = %d^%d",N,ans[0],P);
        for(i=1;i<K;i++)
            printf(" + %d^%d",ans[i],P);

    }
    else
        printf("Impossible\n");


    return 0;
}

分析

主要思路是DFS。

  1. 预处理先计算出不大于N的所有$i^p$用于后续搜索
  2. cmath中的pow函数返回值为double,在转换成int的时候是直接截断,例如10^2=100,在某些编译器下会出现(int)pow(10,2) => 99 ,所以只好自己写一个pow
  3. DFS参数:当前搜索index,搜索到第nowK个数,因子和factSum,$i^p$ 之和powSum
  4. 刚进入DFS的时候nowK是0
  5. DFS的各种条件挺烦人的,还有vector在codebloks里无法调试,多注意吧
Licensed under CC BY-NC-SA 4.0
Built with Hugo
主题 StackJimmy 设计