Funny Substrings (Codeforces 1538E)
Tags: Implement, matrices

Polycarp came up with a new programming language. There are only two types of statements in it:   "x := s": assign the variable named x the value s (where s is a string). For example, the statement var := hello assigns the variable named var the value hello. Note that s is the value of a string, not the name of a variable. Between the variable name, the := operator and the string contains exactly one space each. "x = a + b": assign the variable named x the concatenation of values of two variables a and b. For example, if the program consists of three statements a := hello, b := world, c = a + b, then the variable c will contain the string helloworld. It is guaranteed that the program is correct and the variables a and b were previously defined. There is exactly one space between the variable names and the = and + operators. All variable names and strings only consist of lowercase letters of the English alphabet and do not exceed $$$5$$$ characters.The result of the program is the number of occurrences of string haha in the string that was written to the variable in the last statement.Polycarp was very tired while inventing that language. He asks you to implement it. Your task is — for given program statements calculate the number of occurrences of string haha in the last assigned variable.

Input: The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^3$$$). Then $$$t$$$ test cases follow.The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 50$$$) — the number of statements in the program. All variable names and strings are guaranteed to consist only of lowercase letters of the English alphabet and do not exceed $$$5$$$ characters.This is followed by $$$n$$$ lines describing the statements in the format described above. It is guaranteed that the program is correct.

Output: For each set of input data, output the number of occurrences of the haha substring in the string that was written to the variable in the last statement.

Note: In the first test case the resulting value of d is hhahahaha.

Sample Inputs:
4
6
a := h
b := aha
c = a + b
c = c + c
e = c + c
d = a + c
15
x := haha
x = x + x
x = x + x
x = x + x
x = x + x
x = x + x
x = x + x
x = x + x
x = x + x
x = x + x
x = x + x
x = x + x
x = x + x
x = x + x
x = x + x
1
haha := hah
5
haahh := aaaha
ahhhh = haahh + haahh
haahh = haahh + haahh
ahhhh = ahhhh + haahh
ahhaa = haahh + ahhhh

Sample Outputs:
3
32767
0
0

Solution (Python):
import sys
lines = sys.stdin.read().strip().split('\n')

def process(commands):
    state = dict()
    for command in commands:
        execute(command, state)
    target = commands[-1].strip().split()[0]
    return state[target][0]

def execute(command, state):
    tokens = command.strip().split()
    if len(tokens) == 3:
        val = tokens[2]
        state[tokens[0]] = (1 if 'haha' in val else 0, val[:3], val[-3:])
    else:
        (target, op1, op2) = (tokens[0], tokens[2], tokens[4])
        (count1, head1, tail1) = state[op1]
        (count2, head2, tail2) = state[op2]
        total = count1 + count2
        if tail1 == 'hah' and head2 == 'aha':
            total += 2
        elif 'haha' in tail1 + head2:
            total += 1
        if len(head1) < 3:
            head1 = (head1 + head2)[:3]
        if len(tail2) < 3:
            tail2 = (tail1 + tail2)[-3:]
        state[target] = (total, head1, tail2)
t = int(lines[0])
current = 1
for _ in range(t):
    n = int(lines[current])
    current += 1
    print(process(lines[current:current + n]))
    current += n

Solution (Python):
def count_haha(s):
    count = 0
    for i in range(len(s) - 3):
        if s[i] == 'h' and s[i + 1] == 'a' and (s[i + 2] == 'h') and (s[i + 3] == 'a'):
            count += 1
    return count
for _ in range(int(input())):
    n = int(input())
    dic = {}
    ans = 0
    for i in range(n):
        s = input().split()
        if s[1] == ':=':
            dic[s[0]] = (count_haha(s[2]), s[2][:3], s[2][-3:])
        else:
            dic[s[0]] = (dic[s[2]][0] + dic[s[4]][0] + count_haha(dic[s[2]][2] + dic[s[4]][1]), (dic[s[2]][1] + dic[s[4]][1])[:3], (dic[s[2]][2] + dic[s[4]][2])[-3:])
    print(dic[s[0]][0])

Solution (Python):
def count_haha(s):
    cnt = 0
    beg = 0
    while True:
        beg = s.find('haha', beg)
        if beg < 0:
            break
        cnt += 1
        beg += 1
    return cnt

def solve(N, st):
    states = {}
    lastvar = None
    for s in st:
        s = s.split()
        if len(s) == 3:
            (k, v) = (s[0], s[2])
            states[k] = (v[:3], v[-3:], count_haha(v))
        else:
            (k, a, b) = (s[0], s[2], s[4])
            (a_pref, a_suf, a_cnt) = states[a]
            (b_pref, b_suf, b_cnt) = states[b]
            if len(a_pref) < 3 and len(b_pref) < 3:
                ks = a_pref + b_pref
                states[k] = (ks[:3], ks[-3:], count_haha(ks))
            elif len(a_pref) < 3:
                (k_suf, k_cnt) = (b_suf, b_cnt)
                kp = a_suf + b_pref
                k_cnt += count_haha(kp)
                k_pref = kp[:3]
                states[k] = (k_pref, k_suf, k_cnt)
            elif len(b_pref) < 3:
                (k_pref, k_cnt) = (a_pref, a_cnt)
                ks = a_suf + b_pref
                k_cnt += count_haha(ks)
                k_suf = ks[-3:]
                states[k] = (k_pref, k_suf, k_cnt)
            else:
                (k_pref, k_suf) = (a_pref, b_suf)
                k_cnt = a_cnt + b_cnt
                k_cnt += count_haha(a_suf + b_pref)
                states[k] = (k_pref, k_suf, k_cnt)
        lastvar = s[0]
    return states[lastvar][2]
if __name__ == '__main__':
    T = int(input())
    for t in range(T):
        N = int(input())
        st = []
        for n in range(N):
            st.append(input())
        print(solve(N, st))