首页 > 其他 > 详细

把石头分为若干堆

时间:2017-04-07 21:39:00      阅读:95      评论:0      收藏:0      [点我收藏+]

题目:n块石头分为若干堆放在一条直线,要求每堆至少有一块石头,相邻两堆数目不同。求所有的分堆方法中,堆中石头大于k的最大的次数。

思路:贪心算法

代码:

import java.util.Scanner;

public class Main2 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int k = sc.nextInt();

        System.out.println(helper(n, k));
    }

    public static int helper(int n, int k) {
        if (k > n) return 0;
        int res = 0;
        int flag = 0;
        while (n > 0) {
            if (n-k-flag >= 0) {
                res++;
                n = n - k - flag;
                flag = 1 - flag;
            } else break;
        }

        return res;
    }
}

 

把石头分为若干堆

原文:http://www.cnblogs.com/liujinhong/p/6679892.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!