经典笔试题:小q的歌单(背包问题)

小Q有X首长度为A的不同的歌和Y首长度为B的不同的歌,现在小Q想用这些歌组成一个总长度正好为K的歌单,每首歌最多只能在歌单中出现一次,在不考虑歌单内歌曲的先后顺序的情况下,请问有多少种组成歌单的方法。
输入描述:
每个输入包含一个测试用例。
每个测试用例的第一行包含一个整数,表示歌单的总长度K(1<=K<=1000)。
接下来的一行包含四个正整数,分别表示歌的第一种长度A(A<=10)和数量X(X<=100)以及歌的第二种长度B(B<=10)和数量Y(Y<=100)。保证A不等于B。

输出描述:
输出一个整数,表示组成歌单的方法取模。因为答案可能会很大,输出对1000000007取模的结果。
链接:https://www.nowcoder.com/questionTerminal/f3ab6fe72af34b71a2fd1d83304cbbb3?orderByHotValue=1&page=1&onlyReference=false
来源:牛客网

可作为背包问题求解,属于“填满”类型求方案总数问题
这里借鉴背包思想,采用一个二维数组保存每次的方案数量。

import java.util.Scanner;

public class Main{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int k = sc.nextInt();
        int a = sc.nextInt();
        int x = sc.nextInt();
        int b = sc.nextInt();
        int y = sc.nextInt();

        long[][] count = new long[105][105];
        count[0][0] = 1;
        long ans=0;
        for(int i = 1;i <= 100; i++){
            count[i][0] = 1;
            for(int j = 1 ;j <= 100; j++){
                count[i][j] = (count[i-1][j-1] + count[i-1][j])%1000000007;
            }
        }

        for(int i = 0;i <= x; i++){
            if(i*a <= k &&(k-i*a)%b == 0 && (k-a*i)/b <= y){
                ans = (ans+(count[x][i] * count[y][(k-a*i)/b])%1000000007)%1000000007;
            }
        }
        System.out.println(ans);
    }
}

你可能感兴趣的:(笔试)