第十四届华中科技大学程序设计竞赛 B Beautiful Trees Cutting【组合数学/费马小定理求逆元/快速幂】
链接:https://www.nowcoder.com/acm/contest/106/B
来源:牛客网
题目描述
It’s universally acknowledged that there’re innumerable trees in the campus of HUST.
One day Xiao Ming is walking on a straight road and sees many trees line up in the right side. Heights of each tree which is denoted by a non-negative integer from 0 to 9 can form a tree string. It's very surprising to find that the tree string can be represent as an initial string repeating K times. Now he wants to remove some trees to make the rest of the tree string looks beautiful. A string is beautiful if and only if the integer it represents is divisible by five. Now he wonders how many ways there are that he could make it.
Note that when we transfer the string to a integer, we ignore the leading zeros. For example, the string “00055” will be seen as 55. And also pay attention that two ways are considered different if the removed trees are different. The result can be very large, so printing the answer (mod 1000000007) is enough. And additionally, Xiao Ming can't cut down all trees.
输入描述:
The first line contains a single integer K, which indicates that the tree string is the initial string repeating K times.
The second line is the initial string S.
输出描述:
A single integer, the number of ways to remove trees mod 1000000007.
示例1
输入
1
100
输出
6
说明
Initially, the sequence is ‘100’. There are
6 ways:
100
1_0
10_
_00
__0
_0_
示例2
输入
3
125390
输出
149796
【出处】:CF 327 C
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <stack>
#include <set>
#include <string>
#include <cstdlib>
#include <cmath>
using namespace std;
#define ll long long
#define mod 1000000007
ll Pow(ll a, ll b)
{
ll res=1;
while(b)
{
if(b&1)
res=res*a%mod;
a=a*a%mod;
b>>=1;
}
return res;
}
int main()
{
string s;int k;
while(cin>>k>>s)
{
ll ans=0;
ll n=s.size();
for(int i=0;i<n;i++)
if(s[i]=='0' || s[i]=='5')
ans += Pow(2,i); //原串
ll fm = Pow(2,n);
ll fz = Pow(fm,k);
fz = ((1-fz)%mod+mod)%mod;
fm = ((1-fm)%mod+mod)%mod;
ans = ((ans%mod) * (fz * Pow(fm,mod-2)%mod) ) % mod;
//inv(1-2^n) = pow(1-2^n , mod-2)
printf("%lld\n",ans);
}
return 0;
}