Codeforces Round #191 (Div. 2) C. Magic Five 快速幂
C. Magic Five
链接:
http://codeforces.com/contest/327/problem/C
题解:
求等比为k的等比数列之和T[n]..
当n为偶数..T[n] = T[n/2] + pow(k,n/2) * T[n/2]
当n为奇数...T[n] = T[n/2] + pow(k,n/2) * T[n/2] + 等比数列第n个数的值
比如 1+2+4+8 = (1+2) + 4*(1+2)
1+2+4+8+16 = (1+2) + 4*(1+2) + 16
代码:
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <cmath> 5 #include <algorithm> 6 #include <vector> 7 #include <string> 8 #include <map> 9 #include <set> 10 #include <stack> 11 #include <queue> 12 #include <functional> 13 using namespace std; 14 #define rep(i,a,n) for (int i=a;i<=n;i++) 15 #define per(i,a,n) for (int i=n;i>=a;i--) 16 #define pb push_back 17 #define mp make_pair 18 #define all(x) (x).begin(),(x).end() 19 #define fi first 20 #define se second 21 #define SZ(x) ((int)(x).size()) 22 typedef vector<int> VI; 23 typedef long long ll; 24 typedef pair<int, int> PII; 25 const ll mod = 1000000007; 26 // head 27 28 char s[100004]; 29 ll m; 30 ll POW(ll a, ll k) 31 { 32 ll x, ans = 1; 33 x = a; 34 while (k) { 35 if (k % 2) ans = (ans*x) % mod; 36 x = (x*x) % mod; 37 k /= 2; 38 } 39 return ans; 40 } 41 ll T(ll n, ll t) 42 { 43 if (n == 1) return t; 44 ll data = T(n / 2, t); 45 data = (data + data*POW(m, n / 2)) % mod; 46 if (n % 2) data = (data + POW(m, (n - 1))*t) % mod; 47 return data; 48 } 49 int main() 50 { 51 int k, i; 52 ll ans, x, len; 53 scanf("%s", s); 54 scanf("%d", &k); 55 len = strlen(s); 56 m = POW(2, len); 57 ans = 0; 58 x = 1; 59 for (i = 0; i<len; i++){ 60 if (s[i] == '0' || s[i] == '5') 61 ans = (ans + x) % mod; 62 x = (x * 2) % mod; 63 } 64 ans = T(k, ans); 65 printf("%I64d\n", ans); 66 return 0; 67 }