Uva-1347 Power Calculus

題目鏈接:Power Calculus

題目大意:給出n,求最少多少次乘除操作使 x 變成 xn ,每次操作只能取不大於自己指數的元素。

解題思路:由於不知道最後的深度是多少,直接上DFS一定會超時,所以改用迭代加深搜索,在搜索過程中注意剪枝。

代碼如下:

#include <map>
#include <set>
#include <queue>
#include <stack>
#include <cstdio>
#include <vector>
#include <cstdlib>
#include <cstring>
#include <iomanip>
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long ll;
typedef pair<int, int> P;
const int inf = 0x3f3f3f3f;
const int maxn = 2e4 + 15;

int n, dp[1005], cnt, maxd;

bool DFS(int x, int dep){
    if(dep >= maxd) return x == n;
    int ma = *max_element(dp, dp + cnt);
    if(ma << maxd - dep < n) return false;
    for(int i = cnt - 1; i >= 0; i--){
        dp[cnt++] = x + dp[i];
        if(DFS(x + dp[i], dep + 1)) return true;
        cnt--;
        dp[cnt++] = x - dp[i];
        if(DFS(x - dp[i], dep + 1)) return true;
        cnt--;
    }
    return false;
} 


int main(){
#ifdef LOCAL
    freopen("in.txt", "r", stdin);
#endif
    ios::sync_with_stdio(false);
    cin.tie(0);
    memset(dp, 0, sizeof dp);
    while(cin >> n && n){
        if(dp[n]) goto Answer;
        for(maxd = __lg(n); ; maxd++){
            cnt = 1; dp[0] = 1;
            if(DFS(1, 0)) break;    
        }
        Answer:
            cout << maxd << endl;
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章