The number of binary strings that must have 1 on the left of 0

The number of binary strings that must have 1 on the left of 0

Title description

Given an integer n, find the number of strings with a "1" character on the left side of the "0" character among all character strings consisting of "0" characters and "1" characters in length n.

Enter a description:

Enter a line containing an integer n (1 ≤ n ≤ 2 ∗ 1 0 7) n(1 \leq n \leq2*10^7)n(1n2107)

Output description:

Output an integer to indicate the returned answer. Due to the huge number of strings, it may overflow. Please output 2 29 2^{29}22 The answer after 9 modulo.

Example 1
enter
1
Output
1
Description
只有“1”满足
Example 2
enter
2
Output
2
Description
只有“10”和“11”满足
Example 3
enter
3
Output
3
Description
只有“101”,“110”,“111”满足

answer:

When we draw on paper, we can find that the first few items are: 1 2 3 5 8 13 …, the obvious Fibonacci sequence. The data range is a bit large, O (n) O(n)O ( n ) should not pass, use matrix fast exponentiation and it's done.

Code:
#include <cstdio>
#include <cstring>

using namespace std;

const long MOD = 1 << 29;

int n;
long c[2][2];

void matmul(long a[][2], long b[][2]) {
    
    
    memset(c, 0, sizeof c);
    for (int i = 0; i < 2; ++i) {
    
    
        for (int j = 0; j < 2; ++j) {
    
    
            for (int k = 0; k < 2; ++k) {
    
    
                c[i][j] += a[i][k] * b[k][j] % MOD;
                c[i][j] %= MOD;
            }
        }
    }
    memcpy(a, c, sizeof c);
}

int solve(int m) {
    
    
    long ans[][2] = {
    
     {
    
    1,1}, {
    
    1,0} };
    long ret[][2] = {
    
     {
    
    1,0}, {
    
    0,1} };
    
    while (m) {
    
    
        if (m & 1) matmul(ret, ans);
        matmul(ans, ans);
        m >>= 1;
    }
    return ret[0][0];
}

int main(void) {
    
    
    scanf("%d", &n);
    if (n < 3) return 0 * printf("%d\n", n);
    printf("%d\n", solve(n));
    return 0;
}

Guess you like

Origin blog.csdn.net/MIC10086/article/details/108927740