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 4: Welcome to Code Jam (Hard)

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

Given a string S of length nnn, find the number of times "welcome to code jam" appears as a subsequence in the string.

Idea: use a (n + 1) x 20 DP array to count the number of appearances. (There are 19 letters in the string "welcome to code jam".)

Let's keep track of the target string in a variable target = "welcome to code jam" and the answer in an array dp[n+1][20](initialized to zeros).

For each char in the given string, compare it to each char "welcome to code jam". (Outer loop: go through each letter of the given string S; inner loop: iterate over target.) For the current char S[i] and a char target[l], the count at S[i] is equal to the count at S[i-1] plus the count at S[i] (with respect to target[l]).

Base case:

  • dp[0][0] = 1

Recurrence relation:

  • dp[i + 1][l] = dp[i][l] + dp[i + 1][l]

Additionally, if S[i] == target[l], then we also have dp[i + 1][l + 1] = dp[i][l] + dp[i + 1][l + 1]. Otherwise if they are not equal, then we don't perform the extra addition.

At the end, the answer we are looking for is stored at dp[n][19].

Note: after each arithmetic operation, remember to take the modulo 10000 of the result. Also, be careful with formatting the answer!

PreviousProblem 3: Radio CommercialsNextProblem 5: Honeycomb Walk

Last updated 4 years ago