【codeforces #327C】 Magic Five 矩阵高速幂加等比加逆元

Magic Five
Time Limit:1000MS Memory Limit:262144KB 64bit IO Format:%I64d & %I64u
Submit

Status
Description
There is a long plate s containing n digits. Iahub wants to delete some digits (possibly none, but he is not allowed to delete all the digits) to form his “magic number” on the plate, a number that is divisible by 5. Note that, the resulting number may contain leading zeros.

Now Iahub wants to count the number of ways he can obtain magic number, modulo 1000000007 (109 + 7). Two ways are different, if the set of deleted positions in s differs.

Look at the input part of the statement, s is given in a special form.

Input
In the first line you’re given a string a (1 ≤ |a| ≤ 105), containing digits only. In the second line you’re given an integer k (1 ≤ k ≤ 109). The plate s is formed by concatenating k copies of a together. That is n = |a|·k.

Output
Print a single integer — the required number of ways modulo 1000000007 (109 + 7).

Sample Input
Input
1256
1
Output
4
Input
13990
2
Output
528
Input
555
2
Output
63
Hint
In the first case, there are four possible ways to make a number that is divisible by 5: 5, 15, 25 and 125.

In the second case, remember to concatenate the copies of a. The actual plate is 1399013990.

In the third case, except deleting all digits, any choice will do. Therefore there are 26 - 1 = 63 possible ways to delete digits.

题意:告诉一个串,以及这个串的个数K,将这K个串连接起来,然后可以删除其中一些数字,但是不能全部删除,使得这个串表示的数能被5整除,可以存在包含前导零的情况,05 和 5是两个不同的数。问总共能有多少这种数。

思路:
1.能被5整除,那么要么是0 要么是5结尾,所以对于只有一个串的时候每次都找0 5结尾的数,它前面的可以选或者不选就是总共2^i种可能.
2. (a/b)%c这类运算不能等价于(a%c / b%c)—-可等价为(a*b’)%c…其中b’为b的逆元..

#include<iostream>
#include<stdio.h>
#define MOD 1000000007
#define LL long long 
using namespace std;
string s;
LL ans=0;
LL k;
LL x0;
void ex_gcd(LL a,LL b,LL &x,LL &y)
{
    if(b==0)
    {
        x=1,y=0;return ;
    }
    ex_gcd(b,a%b,y,x);
    y-=a/b*x;
}
LL inverse(LL a,LL m)
{
    LL x,y;
    ex_gcd(a,m,x,y);
    return (x+MOD)%MOD;
}
LL cheng(LL x,LL y)
{
    LL res=1;
    while(y)
    {
        if(y&1)
         res=(res*x)%MOD;

        x=(x*x)%MOD;
        y>>=1;
    }
    return res;
}
int main()
{
    cin>>s>>k;
    LL tmp=1;
    LL n=s.size();

    for(LL i=1;i<=n;i++)
    {
        if(s[i-1]=='0'||s[i-1]=='5')    
        ans=(tmp+ans)%MOD;
        tmp=(2*tmp)%MOD;
    }
    cout<<endl;
    LL an=cheng(tmp,k);
    LL t=(((ans*(an-1))%MOD*inverse(tmp-1,MOD))%MOD+MOD)%MOD;
    cout<<t;
}

你可能感兴趣的:(C语言,codeforces)