题解 | #跳石板#

跳石板

https://www.nowcoder.com/practice/4284c8f466814870bae7799a07d49ec8

#include <iostream>
#include<cmath>
#include<vector>
#include<climits>
using namespace std;

void get_div_num(vector<int>& a, int x) {
    for (int i = 2; i <= sqrt(x); ++i) {
        if (x % i == 0) {
            a.push_back(i);
            if (x / i != i)
                a.push_back(x / i);
        }
    }
}

int Jump(int n, int m) {
    vector<int> step(m + 1, INT_MAX);
    step[n] = 0;
    for (int i = n; i < m; ++i) {
        if (step[i] == INT_MAX)
            continue;
        vector<int> a;
        get_div_num(a, i);
        for (int j = 0; j < a.size(); j++) {
            if(i + a[j] <= m && step[i + a[j]] != INT_MAX) {
                //新的和旧的比较谁的步数少
                step[i + a[j]] = step[i + a[j]] > step[i] + 1 ? step[i] + 1 :step[i + a[j]];
            } else if (a[j] + i <= m) {
                step[a[j] + i] = step[i] + 1;
            }
        }
    }
    return step[m] == INT_MAX ? -1 : step[m];
}

int main() {
    int n, m;
    int min_step = 0;
    while (cin >> n >> m) {
        min_step = Jump(n, m);
        cout << min_step << endl;
    }
    return 0;
}

全部评论

相关推荐

面试摇了我吧:啊哈哈面试提前五个小时发,点击不能参加就是放弃
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务