A Simple Equation
Given N,A,B,C, find how many solutions exist to the equation : a + b + c ≤ N, such that 0 ≤ a ≤ A, 0 ≤ b ≤ B, 0 ≤ c ≤ C.
Input
The first line contains the number of test cases T. Each test case contains 4 integers, N,A,B,C. 0 ≤ N,A,B,C ≤ 2500
Output
Output T lines, one for each test case.
Sample Input
2 4 3 2 1 1 1 1 1
Sample Output
20 4
看起来很简单的问题,不过却牵涉到数学思想。
具体的基础知识可以参考Discrete Mathematics and Its Application 7th第八章的inclusion and exclusion的内容,大师讲的非常好。
数学建模是最难的了。
本题抽象思考 - 把不等式建模为把物体放进盒子问题,设右边的数值为物体数量,左边的三个变量为三个盒子:
因为是小于等于,所以可以选择0 到 N个数字放进3个盒子里面,那么可以假设增加一个盒子,相当于把剩下没选择的数字放进这个盒子里面,那么就相当于有4个盒子放置N个物体的问题了。
听不懂我说什么?后悔没学好离散数学了吧,那需要拿上面那本书好好补补基础知识了。
class ASimpleEquation_2
{
long long comb(int n, int m)
{
if (n < m) return 0LL;
int a = min(m, n-m);
long long up = 1, low = 1;
for (int i = 1; i <= a; i++)
{
up *= (n-i+1);
low *= i;
if (up % low == 0) up /= low, low = 1;
}
return (up / low);
}
public:
ASimpleEquation_2()
{
int T, N, A, B, C;
scanf("%d", &T);
while (T--)
{
scanf("%d %d %d %d", &N, &A, &B, &C);
int a = A+1, b = B+1, c = C+1;
long long t = comb(N-a+3, 3) + comb(N-b+3, 3) + comb(N-c+3, 3);
t -= comb(N-a-b+3, 3) + comb(N-a-c+3, 3) + comb(N-b-c+3, 3);
t += comb(N-a-b-c+3, 3);
t = comb(N+3, 3) - t;
printf("%lld\n", t);//codechef不允许使用%I64d
}
}
};