题解:P10494 [USACO02FEB] Power Hungry Cows

· · 题解

这道题可以用搜索来实现,我用的是迭代加深,也可以用 bfs 等算法。主要考虑剪枝。

下面是代码:

#include <bits/stdc++.h>
using namespace std;

int lim, p, _pow[31];
bool flag = 0;

void dfs(int dep, int x, int y) {
    if (x < y)
        swap(x, y);
    if (dep == lim + 1) {
        if (x == p or y == p) {
            cout << dep - 1 << endl;
            exit(0);
        }
        return ;
    }
    if (gcd(x, y) and p % gcd(x, y) != 0)
        return ;
    if (x * _pow[lim - dep + 1] < p)
        return ;
    dep++;
    dfs(dep, x, y + x);
    dfs(dep, y + x, y);
    dfs(dep, x, x - y);
    dfs(dep, x - y, y);
    dfs(dep, x, x + x);
    dfs(dep, x + x, y);
    dfs(dep, x, y + y);
    dfs(dep, y + y, y);
}

int main() {
    _pow[0] = 1;
    for (int i = 1; i < 32; i++)
        _pow[i] = _pow[i - 1] * 2;
    cin >> p;
    for (lim = 0; !flag; lim++)
        dfs(1, 1, 0);
    return 0;
}