算法学习3

现有n1+n2种面值的硬币,其中前n1种为普通币,可以取任意枚,后n2种为纪念币,每种最多只能取一枚,每种硬币有一个面值,问能用多少种方法拼出m的面值?

在这里插入图片描述

在这里插入图片描述

约瑟夫环

public class Code_JosephusProblem {

    public static class Node {
        public int value;
        public Node next;

        public Node(int data) {
            value = data;
        }
    }

    public static Node josephusKill1(Node head, int m) {
        if (head == null || head.next == head || m < 1) {
            return head;
        }
        Node last = head;
        while (last.next != head) {
            last = last.next;
        }

        int count = 0;
        while (head != last) {
            if (++count == m) {
                last.next = head.next;
                count = 0;
            } else {
                last = last.next;
            }
            head = last.next;
        }
        return head;
    }

    public static Node josephusKill2(Node head, int m) {
        if (head == null || head.next == head || m < 1) {
            return head;
        }
        Node cur = head.next;
        int tmp = -1; // tmp -> list size
        while (cur != head) {
            tmp++;
            cur = cur.next;
        }
        tmp = getLive(tmp, m); // tmp -> service node position
        while (--tmp != 0) {
            head = head.next;
        }
        return head;
    }

    // 现在一共有i个节点,数到m就杀死节点,最终会活下来的节点,请返回它在有i个节点时候的编号
    // 旧
    // getLive(N, m)
    public static int getLive(int i, int m) {
        if (i == 1) {
            return 1;
        }
        return (getLive(i - 1, m) + m - 1) % i + 1;
    }

    // 0...n-1 个人围成一圈,依次循环取用arr中的数字
    // 杀n-1轮,返回活的人的原始编号
    public static int live(int n, int[] arr) {
        return no(n, arr, 0);
    }

    // 还剩i个人,当前取用数字是arr[index],并且下面的过程,从index出发
    // 循环取用,返回那个人会活(在i个人中的编号)
    public static int no(int i, int[] arr, int index) {
        if (i == 1) {
            return 1;
        }
        // 老 = (新 + m - 1) % i + 1
        return (no(i - 1, arr, nextIndex(arr.length, index)) + arr[index] - 1) % i + 1;
    }

    // 如果数组长度为size,当前下标为index,返回循环的模型下,下一个index是多少
    public static int nextIndex(int size, int index) {
        return index == size - 1 ? 0 : index + 1;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值