Description
Dear Uncle Jack is willing to give away some of his collectable CDs to his nephews. Among the titles you can find very rare albums of Hard Rock, Classical Music, Reggae and much more; each title is considered to be unique. Last week he was listening to one of his favorite songs, Nobody’s fool, and realized that it would be prudent to be aware of the many ways he can give away the CDs among some of his nephews.
So far he has not made up his mind about the total amount of CDs and the number of nephews. Indeed, a given nephew may receive no CDs at all
Please help dear Uncle Jack, given the total number of CDs and the number of nephews, to calculate the number of different ways to distribute the CDs among the nephews.
Input
The input consists of several test cases. Each test case is given in a single line of the input by, space separated, integers N (1 ≤ N ≤ 10) and D (0 ≤ D ≤ 25), corresponding to the number of nephews and the number of CDs respectively. The end of the test cases is indicated with N = D = 0.
Output
The output consists of several lines, one per test case, following the order given by the input. Each line has the number of all possible ways to distribute D CDs among N nephews.
Sample Input
1 20
3 10
0 0
Sample Output
1
59049
分析思路:
题意非常清楚,就是求N^D这个幂值。有三点需要注意,(1)由于10^25已经出了long long的表示范围,所以可以考虑用数组的形式来进行计算(2)为了加速求幂的过程,可以使用快速幂的方式,由于25很小,其实用朴素的方法也可以。(3)输出格式,结果不要有前导0,中间为0的部分要定满。
#include<iostream>
#include<iomanip>
using namespace std;
const int INF = 1000000000;
const int D = 3;
long long a[D],b[D],c[D];
void mul(long long*m,long long*n)
{
long long t;
for(int i=0;i<D;++i)
c[i] = 0;
for(int i=D-1;i>=0;--i)
{ t = 0;
for(int j=D-1;j>=0;--j)
{
t = m[i]*n[j];
int k = i-(D-1-j);
while(t!=0&&k>=0)
{
c[k] += t%INF;
t /= INF;
--k;
}
}
}
for(int i=0;i<D;++i)
m[i] = c[i];
}
void print()
{
int i=0;
while(a[i]==0) ++i;
cout<<a[i];
for(++i;i<D;++i)
{
cout<<setw(9)<<setfill('0')<<a[i];
}
cout<<endl;
}
void fastPow(int n)
{
while(n!=0)
{
if(n&1)
{
mul(a,b);
}
n >>= 1;
mul(b,b);
}
print();
}
int main()
{
int N,D;
while(1)
{
cin>>N>>D;
if(N==0&&D==0)
break;
else
{
if(D==0)
{
cout<<1<<endl;
continue;
}
a[0] = a[1] = 0;a[2] = 1;
b[0] = b[1] = 0;b[2] = N;
fastPow(D);
}
}
return 0;
}
最后欢迎大家访问我的个人网站: 1024s