Problem C. Partition
Problem Description
Define f(n) as the number of ways to perform n in format of the sum of some positive integers. For instance, when n=4, we have
4=1+1+1+1
4=1+1+2
4=1+2+1
4=2+1+1
4=1+3
4=2+2
4=3+1
4=4
totally 8 ways. Actually, we will have f(n)=2 (n-1) after observations.
Given a pair of integers n and k, your task is to figure out how many times that the integer k occurs in such 2 (n-1) ways. In the example above, number 1 occurs for 12 times, while number 4 only occurs once.
题解:
我们可以特判出n <= k的情况。
4=1+1+1+1
4=1+1+2
4=1+2+1
4=2+1+1
4=1+3
4=2+2
4=3+1
4=4
totally 8 ways. Actually, we will have f(n)=2 (n-1) after observations.
Given a pair of integers n and k, your task is to figure out how many times that the integer k occurs in such 2 (n-1) ways. In the example above, number 1 occurs for 12 times, while number 4 only occurs once.
对于1 <= k < n,我们可以等效为n个点排成一列,并取出其中的连续k个
情况考虑:
第一种情况,被选出的不包含端点,那么有(n – k − 1)种情况完成上述操作,
之间还有(n – k − 2)个位置,可以在每个位置断开,所以共2^(n−k−2) ∗ (n−k
第二种情况,即被选出的包含端点,那么有2种情况,并且剩余共(n – k − 1
2 ∗ 2^(n – k − 1)种方法。
总计2 ∗ 2^(n – k − 1) + 2^(n – k − 2) ∗ (n – k − 1) = (n – k + 3) * 2^(n – k − 2)。
上述结果,也可以打表找规律(告诉我们 f(n)=2(n-1) ).
f(n,k)=(d+3)*2(d-2) ,其中d=n-k,
但是这里d-2可能很大,如果直接 2(d-2) 次循环的话,会超时。
要学会用二进制处理这种情况。
话不多说,贴代码:
/****************************************************/
#include <iostream>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <stack>
#include <map>
#include <queue>
#include <algorithm>
#define EPS 1e-8
#define MOD 1000000007
using namespace std;
typedef long long LL;
/****************************************************/
int n,k;
int main()
{
int i,j,t,d;
LL ans,e;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&n,&k);
if(n<k) puts("0");
else if(n==k) puts("1");
else{
d=n-k;
if(d==1) puts("2");
else if(d==2) puts("5");
else{
ans=1;
n=d-2; e=2;
while(n)
{
if(n&1) ans=ans*e%MOD;
e=e*e%MOD;
n>>=1;
}
ans=ans*(d+3)%MOD;
printf("%lld\n",ans);
}
}
}
return 0;
}