Beautiful Trees Cutting (inverse element)

Link: https://www.nowcoder.com/acm/contest/106/B
Source: Niuke.com

Topic description


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.

Enter description:

 
  
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 .

Output description:

A single integer, the number of ways to remove trees mod 1000000007.
Example 1

enter

1
100

output

6

illustrate

Initially, the sequence is ‘100’. There are
6 ways:
100
1_0
10_
_00
__0
_0_
Example 2

enter

3
125390

output

149796
#include<cstdio>
#include<algorithm>
#include<iostream>
#include<queue>
#include<cstring>
#include<map>
using namespace std;
typedef long long ll;
 
const int mod=1e9+7;
const int maxn=1e5+10;
int val[maxn];
char str[maxn];
/*
proportional sequence
inverse element
*/
 
ll q_pow(ll base,int n){
    ll ans=1;
    while(n){
        if(n&1)
            ans=(ans*base)%mod;
        base=(base*base)%mod;
        n/=2;
    }
    return ans;
}
 

ll exgcd(ll a,ll b,ll &x,ll &y){
    if(a==0&&b==0) return -1;
    if(b==0){
        x=1,y=0;return a;
    }
    ll d=exgcd(b,a%b,y,x);
    y-=a/b*x;
    return d;
}
 
ll NY(ll a,ll n){
    ll x,y;
    ll d=exgcd(a,n,x,y);
    if(d==1) return (x%n+n)%n;
    else return -1;
}

 
int main(){
    ll k;
    scanf("%lld",&k);
    scanf("%s",str);
    int len ​​= strlen (str);
    for(int i=len-1;i>=0;i--){
        if(str[i]=='0'||str[i]=='5'){
            val[i]=i;
        }
    }
    ll ans=0;
    for(int i=0;i<len;i++){
        if(str[i]=='0'||str[i]=='5')
        ans=(ans+q_pow((ll)2,val[i]))%mod;
    }

    ll q=q_pow((ll)2,len);

    ll _q=NY(q-1,mod);
    ans = (ans * (q_pow (q, k) -1)% mod * _q% mod + mod)% mod;

 	printf("%lld\n",ans);
    return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325823398&siteId=291194637