LogoLogo
  • CP Gymnasium
  • Week 3 Math / Number Theory
    • Week 3 Math / Number Theory
      • Problem 1: Tetration
      • Problem 2: Peragrams
      • Problem 3: Veci
      • Problem 4: Architecture
      • Problem 5: Joint Attack
      • Problem 6: How Many Digits?
      • Problem 7: Abstract Painting
  • Week 4 Array / Greedy
    • Week 4 Array / Greedy
      • Problem 1: Vaccine Efficacy
      • Problem 2: Frosh Week
      • Problem 3: Inquiry
      • Problem 4: Bank Queue
      • Problem 5: Log Land
  • Week 6 Sorting / Binary Search
    • Week 6 Sorting / Binary Search
      • Problem 1: Falling Apart
      • Problem 2: Synchronizing Lists
      • Problem 3: Distributing Ballot Boxes
      • Problem 4: Financial Planning
      • Problem 5: Big Boxes
  • Week 7 Dynamic Programming
    • Week 7 Dynamic Programming
      • Problem 1: Ocean's Anti-11
      • Problem 2: Batmanacci
      • Problem 3: Radio Commercials
      • Problem 4: Welcome to Code Jam (Hard)
      • Problem 5: Honeycomb Walk
  • Week 8 Graph Traversals
    • Week 8 Graph Traversals
      • Problem 1: Reachable Roads
      • Problem 2: Money Matters
      • Problem 3: Squawk Virus
      • Problem 4: Beehives
      • Problem 5: Running MoM
      • Problem 6: Amanda Lounges
Powered by GitBook
On this page
  1. Week 7 Dynamic Programming
  2. Week 7 Dynamic Programming

Problem 1: Ocean's Anti-11

https://open.kattis.com/problems/anti11

PreviousWeek 7 Dynamic ProgrammingNextProblem 2: Batmanacci

Last updated 4 years ago

Given nnn, find the number of binary strings of lengthnnnthat do not contain 11 as a substring.

We can consider 2 types of binary strings: those that end in 0, and those that end in 1.

Consider a string that ends in 1: if we want to extend it by a letter, then the next value must be 0. Otherwise, if we want to extend a string ending in 0, the next value can be either 1 or 0.

Let's think about this backwards:

  • If the current string ends in 1, then the previous string (which we extended by one letter) must have ended in 0.

    • Thus, the number of strings ending in 1 of the current length nnnmust equal to the number strings ending in 0 of length n−1n - 1n−1.

  • If the current string ends in 0, then the previous string could have ended in 0 or 1.

    • Thus, the number of strings ending in 0 of length nnnequals to the number strings ending in 0 of length n−1n - 1n−1, plus the number of strings ending in 1 of length n−1n - 1n−1.

Base cases:

  • end0[0] = 0, end0[1] = 1

    • there are 0 strings of length 0 ending in 0

    • there is 1 string of length 1 ending in 0

  • end1[0] = 0, end1[1] = 1

    • there are 0 strings of length 0 ending in 1

    • there is 1 string of length 1 ending in 1

Recurrence relation:

  • end0[i] = end0[i-1] + end1[i-1]

  • end1[i] = end0[i-1]

The final answer is given by end0[n] + end1[n].

Remember to useunsigned long longand take modulo 1000000007 after each addition.