HDU - 2079 course selection time (generating function)

Problem Description

It's time for course selection again, xhd looked at the course selection table in a daze, in order to make the next semester easier, he wanted to know how many combinations of n credits there are. Come and help him. (xhd thinks that there is no difference between courses of the same credit)

Input

The first line of the input data is a data T, indicating that there are T groups of data.
The first row of each set of data is two integers n (1 <= n <= 40), k (1 <= k <= 8).
Then there are k lines, each line has two integers a (1 <= a <= 8), b (1 <= b <= 10), indicating that the class with the credit of a has b.

Output

For each set of input data, output an integer representing the number of combinations of n credits.

Sample Input

2
2 2
1 2
2 1
40 8
1 1
2 2
3 2
4 2
5 8
6 9
7 6
8 8

Sample Output

2
445

Problem solving ideas:

Classical Generating Function Problem

Code:

#include <cstdio>
#include <cstring>
using namespace std;

int a[10];   //课程学分
int b[10];   //课程数量
int ways[45];
int temp[45];
int main(){
    freopen("D://testData//2079.txt" , "r" , stdin);
    int t , n , k , i , j;
    scanf("%d" ,&t);
    while(t --){
        scanf("%d %d", &n , &k);
        memset(ways , 0 , sizeof(ways));
        memset(temp , 0 , sizeof(temp));

        for(i = 0 ; i < k ; i ++)
            scanf("%d %d",&a[i] , &b[i]);

        for(i = 0 ; i <= b[0]*a[0] && i <= n ; i = i + a[0]){
            ways[i] = 1;
        }

        for(i = 1 ; i < k ; i ++){//加入选择的课程的编号
            for(j = 0 ; j <= n ; j ++){   //需要到达的总学分数
                for(int s = 0 ; s <= a[i] * b[i] && s + j <= n ; s = s + a[i]){
                        temp[s+j] = temp[s+j] + ways[j];
                }
            }

            for(j = 0 ; j <= n ; j ++){
                ways[j] = temp[j];
                temp[j] = 0;
            }
        }

        printf("%d\n" , ways[n]);
    }
    return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325748074&siteId=291194637