Java教程

取硬币

本文主要是介绍取硬币,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

链接

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

import java.util.Arrays;
import java.util.Scanner;

public class Main {

    private static final int MOD = 1000000007;

    private static int[] dp1(int[] coins, int k) {
        int[] dp = new int[k + 1];
        for (int i = 0; i <= k; i += coins[0]) {
            dp[i] = 1;
        }

        for (int i = 1; i < coins.length; ++i) {
            for (int j = coins[i]; j <= k; ++j) {
                dp[j] = (dp[j] + dp[j - coins[i]]) % MOD;
            }
        }
        return dp;
    }

    private static int[] dp2(int[] coins, int k) {
        int[] dp = new int[k + 1];
        dp[0] = 1;
        if (coins[0] <= k) {
            dp[coins[0]] = 1;
        }

        for (int i = 1; i < coins.length; ++i) {
            for (int j = k; j >= coins[i]; --j) {
                dp[j] = (dp[j] + dp[j - coins[i]]) % MOD;
            }
        }
        return dp;
    }

    private static int solve(int[] coins1, int[] coins2, int k) {
        int[] dp1 = dp1(coins1, k);
        int[] dp2 = dp2(coins2, k);

        int ret = 0;

        for (int i = 0; i <= k; ++i) {
            ret = (int) (ret + 1L * dp1[i] * dp2[k - i] % MOD) % MOD;
        }

        return ret;
    }


    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNext()) {
            int n = in.nextInt();
            int m = in.nextInt();
            int k = in.nextInt();
            int[] coin1 = new int[n];
            for (int i = 0; i < n; ++i) {
                coin1[i] = in.nextInt();
            }
            int[] coin2 = new int[m];
            for (int i = 0; i < m; ++i) {
                coin2[i] = in.nextInt();
            }
            System.out.println(solve(coin1, coin2, k));
        }
    }
}
这篇关于取硬币的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!