PAT 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<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 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,⋯,aK } is said to be larger
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
題目大意:給定數N ,K,P 求是否有這樣的K個數(可重複)使得這些數的P次方相加之和等,若有(可能有多個)則求出這樣一個遞減數列a,使得1≤L≤K and i<L,ai==bi aL>bL ,否則輸出“Impossible”。
思路: 1.由於此題N<=400資料量較小,且重複同一個操作,即不斷的加某一個數的平方並驗證是否等於N,所以可選擇用深度搜索演算法。(普通深度搜索會造成有一個樣例超時)
2.首先用一個數組num將平方在[0,N]之間的數儲存,num[i]對應儲存i的平方數。
3.開始深搜,首先建立一個K個空間的陣列temp,它用來儲存每一次深搜過程中加的數i,用sum來求i的平方的和,
4.用tempMax來儲存深搜過程中所加i的總和(原因:篩選出符合題意的那個數列,即最小的數 最大那個數列),由於是從num.size()-1開始深搜,所以如果b數列的tempMax小於a數列的tempMax的話,一定有a[L]>b[L]。(如果不判斷,有一個測試樣例會答案錯誤)。
5,如果用普通深搜,每一次都從0開始遍歷,將會超時,因此可以剪枝,因為輸出數列是降序,所以如果我們第層遞迴為第i個數,那麼下一層遞迴就從第i個數開始,這樣可以把計算量縮小一半。
坑點:1.篩選滿足題意的數列,第L位最大的數列不一定位滿足要求的數列,還必須滿足前提a[i]==b[i] 。因此利用遞減數列求和比較可以篩選出(思路的第3點)
2.必須裁剪遞迴樹,否則會超時(思路 第3點)。
感謝:感謝柳婼大佬的部落格,讓我發現自己 篩選出符合題意的數列的思維漏洞。
#include<iostream>
#include<vector>
#include<math.h>
using namespace std;
vector<int>result;
int n, k, p,Max=0;
//遞迴
void DFS(vector<int>&temp, vector<int>&num, int deep, int sum, int i,int tempMax) {
//每一層加入一個數,在第K層時判斷是否更新result最終陣列
if (deep == k) {
if (sum == n && Max<tempMax) {
result.assign(temp.begin(), temp.end());
}
return;
}
for (; i >=1; i--) {
//遞迴滿足的條件
if (sum +num[i] <= n){
temp[deep]=i;
DFS(temp, num, deep + 1, sum + num[i], i,tempMax+num[i]);
}
}
}
int main() {
cin >> n >> k >> p;
vector<int>num;
num.push_back(0);
//輸入數列,第num[i]對應i的平方
for (int i = 1; pow(i, p) <= n; i++) {
num.push_back(pow(i,p));
}
vector<int>temp(k,0);//用來暫時儲存記錄的數字i
result.resize(k,0);//最終結果數列
DFS(temp, num, 0, 0,num.size()-1);//遞迴深搜
//輸出
if (result[k-1] == 0) {
cout << "Impossible" << endl;
}
else {
printf("%d = ", n);
for (int i = 0; i<result.size(); i++) {
if (i != 0) printf(" + ");
printf("%d^%d", result[i], p);
}
}
}