light oj 1102 - Problem Makes Problem组合数学(隔板法)
As I am fond of making easier problems, I discovered a problem. Actually, the problem is 'how can you make n by adding k non-negative integers?' I think a small example will make things clear. Suppose n=4 and k=3. There are 15 solutions. They are
1. 0 0 4
2. 0 1 3
3. 0 2 2
4. 0 3 1
5. 0 4 0
6. 1 0 3
7. 1 1 2
8. 1 2 1
9. 1 3 0
10. 2 0 2
11. 2 1 1
12. 2 2 0
13. 3 0 1
14. 3 1 0
15. 4 0 0
As I have already told you that I use to make problems easier, so, you don't have to find the actual result. You should report the result modulo 1000,000,007.
Input
Input starts with an integer T (≤ 25000), denoting the number of test cases.
Each case contains two integer n (0 ≤ n ≤ 106) and k (1 ≤ k ≤ 106).
Output
For each case, print the case number and the result modulo 1000000007.
Sample Input |
Output for Sample Input |
4 4 3 3 5 1000 3 1000 5 |
Case 1: 15 Case 2: 35 Case 3: 501501 Case 4: 84793457
|
分析:
题目意思是把 n个元素分成k组且允许有空位置, 这就用到隔板法中的允许若干个人(或位置)为空的问题, 因为把元素分成k组需要k-1个隔板,并且可以允许元素个数为空,所以隔板可以放在任意位置,隔板加上元素个数一共有n+k-1个位置,那么就相当于从n+k-1个位置中选出k-1个位置放隔板即c(n-k+1, k-1)。然后直接用费小马定理(a/b)%mod = a * (b(^mod-2))%mod;求下逆元就可以了。
代码:
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<queue>
#include<stack>
#define N 2000010
#define mod 1000000007
using namespace std;
long long d[N];
void init()
{
d[0] = 1;
for(int i = 1; i < N; i++)
d[i] = (i * d[i-1]) % mod;
}
long long quickmi(long long a, long long b)
{
long long sum = 1;
while(b)
{
if(b & 1)
sum = (sum * a) % mod;
a = (a * a) % mod;
b /= 2;
}
return sum;
}
int main(void)
{
int T , cas;
int n, k;
scanf("%d", &T);
init();
cas = 0;
while(T--)
{
cas++;
scanf("%d%d", &n, &k);
long long ans = quickmi((d[k-1] * d[n]) % mod, mod-2);
ans = (d[n+k-1] * ans ) % mod;
printf("Case %d: %lld\n", cas, ans);
}
return 0;
}
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET制作智能桌面机器人:结合BotSharp智能体框架开发语音交互
· 软件产品开发中常见的10个问题及处理方法
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
· 互联网不景气了那就玩玩嵌入式吧,用纯.NET开发并制作一个智能桌面机器人(四):结合BotSharp
· 一个基于 .NET 开源免费的异地组网和内网穿透工具
· 《HelloGitHub》第 108 期
· Windows桌面应用自动更新解决方案SharpUpdater5发布
· 我的家庭实验室服务器集群硬件清单