【动态规划】跳石板

跳石板_牛客题霸_牛客网 

import java.util.*;
public class Main{
    public static void main(String[] args){
        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();
        int m = scan.nextInt();
        //定义步数,最多能走m+1步
        int[] step = new int[m+1];
        for(int i = 0;i < m+1;i++){
            //初始化step[i]为最大值
            step[i] = Integer.MAX_VALUE;
        }
        //从n石板起跳,默认步数为0
        step[n] = 0;
        for(int i = n;i < m;i++){
            //跳不到最后一个石板
            if(step[i] == Integer.MAX_VALUE){
                continue;
            }
            //求i的约数
            List list = div(i);
            for(int j:list){
                if(i+j <= m && step[i+j] != Integer.MAX_VALUE){
                    step[i+j] = Math.min(step[i+j],step[i]+1);
                }else if(i+j <= m){
                    step[i+j] = step[i]+1;
                }
            }
        }
        if(step[m] == Integer.MAX_VALUE){
                System.out.println(-1);
            }else{
                System.out.println(step[m]);
            }
    }
    public static List div(int num){
        //定义一个链表
        List list = new ArrayList<>();
        //题目中要求约数除去1和它本身,所以要从2开始
        for(int i = 2;i*i <= num;i++){
            if(num%i == 0){
                list.add(i);
                if(num/i != i){
                    list.add(num/i);
                }
            }
        }
        return list;
    }
}

你可能感兴趣的:(每日一题,动态规划,java)