joj 1172 The Equation Problem 组合数学

题目:

Mathematicians are able to solve many a mythical problem. They indeed do much for the mankind. But sometimes they play trick to make some difficult problems for us to solve. The equation problem is one of them. Consider the equation like this: x1+x2+...+xn=p, where both of n(n<=15) and p(p<=30) are positive integers and x1...xn are unkowns. The task is for you given n positive integers a1...an, to write a program to determine how many solutions for this kind of equation for some pair of n and p, where xi>=ai.

For example, assume the equation is x1+x2=5, and a1=2, a2=2. You must calculate the number of solutions which meet the conditions: x1>=a1 and x2>=a2. Obviously, both of x1=2 x2=3 and x1=3 x2=2 satisfy the conditions. And no other solution at all. So the number of total solutions is 2. You need only answer the number.

Input Specification

The input consists of M equations, the first line of input is an integer M. Then follow M equations' descriptions, each of which is in the form of below:

n p
a1 a2 ... an

Integers are separated by spaces.

Output Specification

For each equation, you should print a single line containing the number of solutions.

 

解法:

由于题目要求,最后的方程形式为:

对每个a求和,有:

将上述两个式子相减,得到:

这个方程在组合数学中出现过,它的解的个数等于具有k种类型元素的多重集合的r组合数,其结果等于:

对于这个题目来说,r就是p-ak就是n

代码如下:

  1. #include <cstdio>
  2. int main() {
  3.     freopen("in.txt""r", stdin);
  4.     int m, n, p;
  5.     scanf("%d", &m);
  6.     while(m--) {
  7.     scanf("%d%d", &n, &p);
  8.     int a, suma = 0;
  9.     for(int i = 0; i < n; i++) {
  10.         scanf("%d", &a);
  11.         suma+=a;
  12.     }
  13.     if(p == suma) {
  14.         printf("1/n");
  15.         continue;
  16.     }
  17.     if(p < suma) {
  18.         printf("0/n");
  19.         continue;
  20.     }
  21.     int x = p - suma + n - 1, y = (p-suma)>(n-1)?(n-1):(p-suma);
  22.     double ret = 1;
  23.     for(int i = 0; i < y; i++) 
  24.         ret *= (x - i);
  25.     for(int i = 2; i <= y; i++)
  26.         ret /= i;
  27.     printf("%.0lf/n", ret);
  28.     }
  29.     return 0;
  30. }

 

你可能感兴趣的:(Integer,ini,input,each,pair)