package main

import (
	"bufio"
	"fmt"
	"os"
)

var (
	base   = uint64(27)
	hash   = []uint64{}
	hashes = map[uint64]bool{}
)

func solve(s string, k int, n int, value string) int {
	count := 0
	var id byte

	for i := range s {
		count = 0
		for j := i; j < n; j++ {
			id = s[j] - 'a'
			if value[id] == '0' {
				count++
			}
			if count <= k {
				hashes[getHash(s[i:j+1])] = true
			} else {
				break
			}
		}
	}

	return len(hashes)
}

func getHash(s string) uint64 {
	hash[0] = uint64(s[0])

	for i := 1; i < len(s); i++ {
		hash[i] = (hash[i-1]*base + uint64(s[i]))
	}

	return hash[len(s)-1]
}

func main() {
	r := bufio.NewReader(os.Stdin)
	var str, value string
	var k int

	hash = make([]uint64, len(str))
	fmt.Fscanf(r, "%s\n", &str)
	fmt.Fscanf(r, "%s\n", &value)
	fmt.Fscanf(r, "%d\n", &k)

	fmt.Println(solve(str, k, len(str), value))
}


package main

import (
	"bufio"
	"fmt"
	"os"
)

var (
	base      = uint64(127)
	maxN      = 1500 + 10
	mod       = uint64(1e9 + 7)
	powerBase = make([]uint64, maxN)
	hash      = make([]uint64, maxN)
	hashes    = map[uint64]bool{}
)

func solve(s string, k int, n int, value string) int {
	count := 0
	var id byte

	for i := range s {
		count = 0
		for j := i; j < n; j++ {
			id = s[j] - 'a'
			if value[id] == '0' {
				count++
				if count > k {
					break
				}
			}
			hashes[getHash(s[i:j+1])] = true
		}
	}

	return len(hashes)
}

func getHash(s string) uint64 {
	hash[0] = uint64(s[0])

	for i := 1; i < len(s); i++ {
		hash[i] = (hash[i-1]*base + uint64(s[i])) % mod
	}

	return hash[len(s)-1]
}

func initPowerBase() {
	powerBase[0] = 1

	for i := 1; i < maxN; i++ {
		powerBase[i] = powerBase[i-1] * base % mod
	}
}

func main() {
	r := bufio.NewReader(os.Stdin)
	var str, value string
	var k int

	fmt.Fscanf(r, "%s\n", &str)
	fmt.Fscanf(r, "%s\n", &value)
	fmt.Fscanf(r, "%d\n", &k)
	initPowerBase()

	fmt.Println(solve(str, k, len(str), value))
}


package main

import (
	"bufio"
	"fmt"
	"os"
)

var (
	base         = uint64(127)
	maxN         = 1500 + 10
	mod          = uint64(1e9 + 7)
	powerBase    = make([]uint64, maxN)
	hash         = make([]uint64, maxN)
	hashes       = map[uint64]bool{}
	isGoodLetter = map[byte]bool{}
)

func solve(s string, k int, n int) int {
	count := 0

	for i := range s {
		count = 0
		for j := i; j < n; j++ {
			if !isGoodLetter[s[j]] {
				count++
				if count > k {
					break
				}
			}
			hashes[getHash(s[i:j+1])] = true
		}
	}

	return len(hashes)
}

func getHash(s string) uint64 {
	hash[0] = uint64(s[0])

	for i := 1; i < len(s); i++ {
		hash[i] = (hash[i-1]*base + uint64(s[i])) % mod
	}

	return hash[len(s)-1]
}

func initPowerBase() {
	powerBase[0] = 1

	for i := 1; i < maxN; i++ {
		powerBase[i] = powerBase[i-1] * base % mod
	}
}

func main() {
	r := bufio.NewReader(os.Stdin)
	var str, value string
	var k int

	fmt.Fscanf(r, "%s\n", &str)
	fmt.Fscanf(r, "%s\n", &value)
	fmt.Fscanf(r, "%d\n", &k)
	initPowerBase()

	for i := range str {
		id := str[i] - 'a'
		if value[id] == '1' {
			isGoodLetter[str[i]] = true
		}
	}

	fmt.Println(solve(str, k, len(str)))
}


s = [ord(c) - ord('a') for c in raw_input()]
v = raw_input()
k = int(raw_input())

trie = []
trie.append({})
idx = 0

good_dict = {}
for i in xrange(len(v)):
    good_dict[i] = v[i]
res = 0
for i in xrange(len(s)):
    bad_cnt = 0
    now = 0
    for j in xrange(i, len(s)):
        if good_dict[s[j]] == '0':
            bad_cnt += 1
        if bad_cnt > k:
            break
        if not trie[now].has_key(s[j]):
            trie.append({})
            idx += 1
            trie[now][s[j]] = idx
            now = idx
            res += 1
        else:
            now = trie[now][s[j]]
#print res_trie
print res


s = raw_input()
v = raw_input()
k = int(raw_input())

good_dict = {}
for i in xrange(len(v)):
    good_dict[chr(ord('a') + i)] = v[i]
res = 0
res_trie = {'' : {}}
for i in xrange(len(s)):
    bad_cnt = 0
    trie = res_trie['']
    for j in xrange(i, len(s)):
        if good_dict[s[j]] == '0':
            bad_cnt += 1
        if bad_cnt > k:
            break
        if not trie.has_key(s[j]):
            trie[s[j]] = {}
            res += 1
        trie = trie[s[j]]
#print res_trie
print res


# cook your code here
'''input
acbacbacaa
00000000000000000000000000
2
'''
import math
from fractions import gcd
def mp():
	return map(int,str(raw_input()).split())
m=10**9+9
s=raw_input()
s1=raw_input()
k=input()
dp=[[0 for i in range(1502)] for j in range(1502)]
has=[0 for i in range(3502)]
po=[1 for i in range(1502)]
inv=[1 for i in range(1502)]

p=31

for i in range(1,1502):
    po[i]=(po[i-1]*p)%m;
    #inv[i]=pow(p,i*(m-2),m);

for i in range(len(s)):
    has[i+1]=(has[i]+(ord(s[i])-96)*po[i])%m;

for i in range(len(s)):
	for j in range(i,len(s)):
	    if(j!=i):
	    	dp[i][j]=dp[i][j-1]+(s1[ord(s[j])-97]=='1')
	    else:
	        dp[i][j]=int(s1[ord(s[j])-97]=='1')

n=len(s)

cnt=0
for l in range(1,n+1):
    a=[]
    for i in range(n):
        if i+l>n:
            break
        cur=(has[i+l]+m-has[i])%m
        cur=(cur*po[n-1-i])%m
        if l-dp[i][i+l-1]<=k:
            a.append(cur)
    #print a
    cnt+=len(set(a))

print cnt


# cook your code here
'''input
acbacbacaa
00000000000000000000000000
2
'''
import math
from fractions import gcd
def mp():
	return map(int,str(raw_input()).split())

s=raw_input()
s1=raw_input()
k=input()
dp=[[0 for i in range(1502)] for j in range(1502)]
for i in range(len(s)):
	for j in range(i,len(s)):
	    if(j!=i):
	    	dp[i][j]=dp[i][j-1]+(s1[ord(s[j])-97]=='1')
	    else:
	        dp[i][j]=int(s1[ord(s[j])-97]=='1')

a=[]
b=[]

for i in range(len(s)):
	for j in range(i,len(s)):
		if j-i+1-dp[i][j]<=k:
			a.append(s[i:j+1])
a=set(a)
print len(a)


import sys,os,math
from collections import Counter, defaultdict, deque
import bisect
from sys import stdin, stdout
from itertools import repeat
import Queue
import time

# sys.stdin = open('input')
# n, k = map(int, raw_input().split())
# da = map(int, raw_input().split())
# db = map(int, raw_input().split())

mod = 1000049917
def main():
    p = 131
    st = raw_input().strip()
    mask = raw_input().strip()
    k = map(int, raw_input().split())[0]
    ls = len(st)
    n = ls
    psm = [0] * (ls+1)
    mod_p = [1] * (ls+1)
    ans = 0
    for i in range(ls):
        mod_p[i+1] = mod_p[i]*p
        mod_p[i+1] %= mod
    for i, c in enumerate(st):
        psm[i+1] = psm[i] + (1 if mask[ord(c) - ord('a')] =='0' else 0)
    for l in range(1, n+1):
        hh = 0
        for s in range(l):
            hh += (ord(st[s])-ord('a')+1)*mod_p[s]
            hh %= mod
        ha_s = set()
        if psm[l] - psm[0] <= k:
            ha_s.add((hh * mod_p[n-l+1])%mod)
        for s in range(l, n):
            hh += (ord(st[s])-ord('a')+1)*mod_p[s]
            hh -= (ord(st[s-l])-ord('a')+1)*mod_p[s-l]
            hh = (hh+mod)%mod
            if psm[s+1] - psm[s+1-l] > k:
                continue
            new_h = (hh * mod_p[n-s])%mod
            ha_s.add(new_h)
        ans += len(ha_s)
    print ans

main()


import sys,os,math
from collections import Counter, defaultdict, deque
import bisect
from sys import stdin, stdout
from itertools import repeat
import Queue
import time

# sys.stdin = open('input')
# n, k = map(int, raw_input().split())
# da = map(int, raw_input().split())
# db = map(int, raw_input().split())

mod = int(1e9)+7
def main():
    p = 131
    st = raw_input().strip()
    mask = raw_input().strip()
    k = map(int, raw_input().split())[0]
    ls = len(st)
    n = ls
    psm = [0] * (ls+1)
    mod_p = [1] * (ls+1)
    ans = 0
    for i in range(ls):
        mod_p[i+1] = mod_p[i]*p
        mod_p[i+1] %= mod
    for i, c in enumerate(st):
        psm[i+1] = psm[i] + (1 if mask[ord(c) - ord('a')] =='0' else 0)
    for l in range(1, n+1):
        hh = 0
        for s in range(l):
            hh += (ord(st[s])-ord('a')+1)*mod_p[s]
            hh %= mod
        ha_s = set()
        if psm[l] - psm[0] <= k:
            ha_s.add((hh * mod_p[n-l+1])%mod)
        for s in range(l, n):
            hh += (ord(st[s])-ord('a')+1)*mod_p[s]
            hh -= (ord(st[s-l])-ord('a')+1)*mod_p[s-l]
            hh = (hh+mod)%mod
            if psm[s+1] - psm[s+1-l] > k:
                continue
            new_h = (hh * mod_p[n-s])%mod
            ha_s.add(new_h)
        ans += len(ha_s)
    print ans

main()


import sys,os,math
from collections import Counter, defaultdict, deque
import bisect
from sys import stdin, stdout
from itertools import repeat
import Queue
import time

# sys.stdin = open('input')
# n, k = map(int, raw_input().split())
# da = map(int, raw_input().split())
# db = map(int, raw_input().split())

mod = 1000049917
def main():
    p = 131
    p2 = 31
    st = raw_input().strip()
    mask = raw_input().strip()
    k = map(int, raw_input().split())[0]
    ls = len(st)
    n = ls
    psm = [0] * (ls+1)
    mod_p = [1] * (ls+1)
    mod_p2 = [1] * (ls+1)
    ans = 0
    for i in range(ls):
        mod_p[i+1] = mod_p[i]*p
        mod_p[i+1] %= mod
        mod_p2[i+1] = mod_p2[i]*p2
        mod_p2[i+1] %= mod
    for i, c in enumerate(st):
        psm[i+1] = psm[i] + (1 if mask[ord(c) - ord('a')] =='0' else 0)
    for l in range(1, n+1):
        hh = 0
        hh2 = 0
        for s in range(l):
            hh += (ord(st[s])-ord('a')+1)*mod_p[s]
            hh %= mod
            hh2 += (ord(st[s])-ord('a')+1)*mod_p2[s]
            hh2 %= mod
        ha_s = set()
        ha_s2 = set()
        if psm[l] - psm[0] <= k:
            ha_s.add((hh * mod_p[n-l+1])%mod)
            ha_s2.add((hh2 * mod_p2[n-l+1])%mod)
            ans += 1
        for s in range(l, n):
            hh += (ord(st[s])-ord('a')+1)*mod_p[s]
            hh -= (ord(st[s-l])-ord('a')+1)*mod_p[s-l]
            hh = (hh+mod)%mod
            hh2 += (ord(st[s])-ord('a')+1)*mod_p2[s]
            hh2 -= (ord(st[s-l])-ord('a')+1)*mod_p2[s-l]
            hh2 = (hh2+mod)%mod
            if psm[s+1] - psm[s+1-l] > k:
                continue
            new_h = (hh * mod_p[n-s])%mod
            new_h2 = (hh2 * mod_p2[n-s])%mod
            if new_h not in ha_s or new_h2 not in ha_s2:
                ans += 1
            ha_s2.add(new_h2)
            ha_s.add(new_h)
    print ans

main()


import sys,os,math
from collections import Counter, defaultdict, deque
import bisect
from sys import stdin, stdout
from itertools import repeat
import Queue
import time

# sys.stdin = open('input')
# n, k = map(int, raw_input().split())
# da = map(int, raw_input().split())
# db = map(int, raw_input().split())

mod = 1000049917
def main():
    p = 131
    p2 = 31
    st = raw_input().strip()
    mask = raw_input().strip()
    k = map(int, raw_input().split())[0]
    ls = len(st)
    n = ls
    psm = [0] * (ls+1)
    mod_p = [1] * (ls+1)
    mod_p2 = [1] * (ls+1)
    ans = 0
    for i in range(ls):
        mod_p[i+1] = mod_p[i]*p
        mod_p[i+1] %= mod
        mod_p2[i+1] = mod_p2[i]*p
        mod_p2[i+1] %= mod
    for i, c in enumerate(st):
        psm[i+1] = psm[i] + (1 if mask[ord(c) - ord('a')] =='0' else 0)
    for l in range(1, n+1):
        hh = 0
        hh2 = 0
        for s in range(l):
            hh += (ord(st[s])-ord('a')+1)*mod_p[s]
            hh %= mod
            hh2 += (ord(st[s])-ord('a')+1)*mod_p2[s]
            hh2 %= mod
        ha_s = set()
        ha_s2 = set()
        if psm[l] - psm[0] <= k:
            ha_s.add((hh * mod_p[n-l+1])%mod)
            ha_s2.add((hh2 * mod_p2[n-l+1])%mod)
            ans += 1
        for s in range(l, n):
            hh += (ord(st[s])-ord('a')+1)*mod_p[s]
            hh -= (ord(st[s-l])-ord('a')+1)*mod_p[s-l]
            hh = (hh+mod)%mod
            hh2 += (ord(st[s])-ord('a')+1)*mod_p2[s]
            hh2 -= (ord(st[s-l])-ord('a')+1)*mod_p2[s-l]
            hh2 = (hh2+mod)%mod
            if psm[s+1] - psm[s+1-l] > k:
                continue
            new_h = (hh * mod_p[n-s])%mod
            new_h2 = (hh2 * mod_p2[n-s])%mod
            if new_h not in ha_s and new_h2 not in ha_s2:
                ans += 1
            ha_s2.add(new_h2)
            ha_s.add(new_h)
    print ans

main()


import sys,os,math
from collections import Counter, defaultdict, deque
import bisect
from sys import stdin, stdout
from itertools import repeat
import Queue
import time

# sys.stdin = open('input')
# n, k = map(int, raw_input().split())
# da = map(int, raw_input().split())
# db = map(int, raw_input().split())

mod = 1000049917
def main():
    p = 131
    p2 = 31
    st = raw_input().strip()
    mask = raw_input().strip()
    k = map(int, raw_input().split())[0]
    ls = len(st)
    n = ls
    psm = [0] * (ls+1)
    mod_p = [1] * (ls+1)
    mod_p2 = [1] * (ls+1)
    hm = [0] * (ls+1)
    hm2 = [0] * (ls+1)
    ans = 0
    for i in range(ls):
        mod_p[i+1] = mod_p[i]*p
        mod_p[i+1] %= mod
        mod_p2[i+1] = mod_p2[i]*p2
        mod_p2[i+1] %= mod
    for i, c in enumerate(st):
        psm[i+1] = psm[i] + (1 if mask[ord(c) - ord('a')] =='0' else 0)
    for i in range(ls):
        hm[i+1] = hm[i] + (ord(st[i]) - 96) * mod_p[i]
        hm[i+1] %= mod
        hm2[i+1] = hm2[i] + (ord(st[i]) - 96) * mod_p2[i]
        hm2[i+1] %= mod

    for l in range(1, n+1):
        ha_s = set()
        ha_s2 = set()
        for s in range(l-1, n):
            hh = (hm[s+1] - hm[s+1-l] + mod)%mod
            hh2 = (hm2[s+1] - hm2[s+1-l] + mod)%mod
            if psm[s+1] - psm[s+1-l] > k:
                continue
            new_h = (hh * mod_p[n-s])%mod
            new_h2 = (hh2 * mod_p2[n-s])%mod
            if new_h not in ha_s or new_h2 not in ha_s2:
                ans += 1
            ha_s2.add(new_h2)
            ha_s.add(new_h)
    print ans

main()


import sys,os,math
from collections import Counter, defaultdict, deque
import bisect
from sys import stdin, stdout
from itertools import repeat
import Queue
import time

# sys.stdin = open('input')
# n, k = map(int, raw_input().split())
# da = map(int, raw_input().split())
# db = map(int, raw_input().split())

mod = int(1e9)+7
def main():
    p = 31
    st = raw_input().strip()
    mask = raw_input().strip()
    k = map(int, raw_input().split())[0]
    ls = len(st)
    n = ls
    psm = [0] * (ls+1)
    mod_p = [1] * (ls+1)
    ans = 0
    for i in range(ls):
        mod_p[i+1] = mod_p[i]*p
        mod_p[i+1] %= mod
    for i, c in enumerate(st):
        psm[i+1] = psm[i] + (1 if mask[ord(c) - ord('a')] =='0' else 0)
    for l in range(1, n+1):
        hh = 0
        for s in range(l):
            hh += (ord(st[s])-ord('a'))*mod_p[s]
            hh %= mod
        ha_s = set()
        if psm[l] - psm[0] <= k:
            ha_s.add((hh * mod_p[n-l+1])%mod)
        for s in range(l, n):
            hh += (ord(st[s])-ord('a'))*mod_p[s]
            hh -= (ord(st[s-l])-ord('a'))*mod_p[s-l]
            hh = (hh+mod)%mod
            if psm[s+1] - psm[s+1-l] > k:
                continue
            new_h = (hh * mod_p[n-s])%mod
            ha_s.add(new_h)
        ans += len(ha_s)
    print ans

main()


import sys,os,math
from collections import Counter, defaultdict, deque
import bisect
from sys import stdin, stdout
from itertools import repeat
import Queue
import time

# sys.stdin = open('input')
# n, k = map(int, raw_input().split())
# da = map(int, raw_input().split())
# db = map(int, raw_input().split())

mod = int(1e9)+7
def main():
    p = 131
    st = raw_input().strip()
    mask = raw_input().strip()
    k = map(int, raw_input().split())[0]
    ls = len(st)
    n = ls
    psm = [0] * (ls+1)
    mod_p = [1] * (ls+1)
    ans = 0
    for i in range(ls):
        mod_p[i+1] = mod_p[i]*p
        mod_p[i+1] %= mod
    for i, c in enumerate(st):
        psm[i+1] = psm[i] + (1 if mask[ord(c) - ord('a')] =='0' else 0)
    for l in range(1, n+1):
        hh = 0
        for s in range(l):
            hh += (ord(st[s])-ord('a'))*mod_p[s]
            hh %= mod
        ha_s = set()
        if psm[l] - psm[0] <= k:
            ha_s.add((hh * mod_p[n-l+1])%mod)
        for s in range(l, n):
            hh += (ord(st[s])-ord('a'))*mod_p[s]
            hh -= (ord(st[s-l])-ord('a'))*mod_p[s-l]
            hh = (hh+mod)%mod
            if psm[s+1] - psm[s+1-l] > k:
                continue
            new_h = (hh * mod_p[n-s])%mod
            ha_s.add(new_h)
        ans += len(ha_s)
    print ans

main()


import sys,os,math
from collections import Counter, defaultdict, deque
import bisect
from sys import stdin, stdout
from itertools import repeat
import Queue
import time

# sys.stdin = open('input')
# n, k = map(int, raw_input().split())
# da = map(int, raw_input().split())
# db = map(int, raw_input().split())

mod = int(1e9)+7
def main():
    p = 137
    st = raw_input().strip()
    mask = raw_input().strip()
    k = map(int, raw_input().split())[0]
    ls = len(st)
    n = ls
    psm = [0] * (ls+1)
    mod_p = [1] * (ls+1)
    ans = 0
    for i in range(ls):
        mod_p[i+1] = mod_p[i]*p
        mod_p[i+1] %= mod
    for i, c in enumerate(st):
        psm[i+1] = psm[i] + (1 if mask[ord(c) - ord('a')] =='0' else 0)
    for l in range(1, n+1):
        hh = 0
        for s in range(l):
            hh += (ord(st[s])-ord('a')+1)*mod_p[s]
            hh %= mod
        ha_s = set()
        if psm[l] - psm[0] <= k:
            ha_s.add((hh * mod_p[n-l+1])%mod)
        for s in range(l, n):
            hh += (ord(st[s])-ord('a')+1)*mod_p[s]
            hh -= (ord(st[s-l])-ord('a')+1)*mod_p[s-l]
            hh = (hh+mod)%mod
            if psm[s+1] - psm[s+1-l] > k:
                continue
            new_h = (hh * mod_p[n-s])%mod
            ha_s.add(new_h)
        ans += len(ha_s)
    print ans

main()


import sys,os,math
from collections import Counter, defaultdict, deque
import bisect
from sys import stdin, stdout
from itertools import repeat
import Queue
import time

# sys.stdin = open('input')
# n, k = map(int, raw_input().split())
# da = map(int, raw_input().split())
# db = map(int, raw_input().split())

mod = 1000049917
def main():
    p = 131
    p2 = 31
    st = raw_input().strip()
    mask = raw_input().strip()
    k = map(int, raw_input().split())[0]
    ls = len(st)
    n = ls
    psm = [0] * (ls+1)
    mod_p = [1] * (ls+1)
    mod_p2 = [1] * (ls+1)
    ans = 0
    for i in range(ls):
        mod_p[i+1] = mod_p[i]*p
        mod_p[i+1] %= mod
        mod_p2[i+1] = mod_p2[i]*p
        mod_p2[i+1] %= mod
    for i, c in enumerate(st):
        psm[i+1] = psm[i] + (1 if mask[ord(c) - ord('a')] =='0' else 0)
    for l in range(1, n+1):
        hh = 0
        hh2 = 0
        for s in range(l):
            hh += (ord(st[s])-ord('a')+1)*mod_p[s]
            hh %= mod
            hh2 += (ord(st[s])-ord('a')+1)*mod_p2[s]
            hh2 %= mod
        ha_s = set()
        ha_s2 = set()
        if psm[l] - psm[0] <= k:
            ha_s.add((hh * mod_p[n-l+1])%mod)
            ha_s2.add((hh2 * mod_p2[n-l+1])%mod)
            ans += 1
        for s in range(l, n):
            hh += (ord(st[s])-ord('a')+1)*mod_p[s]
            hh -= (ord(st[s-l])-ord('a')+1)*mod_p[s-l]
            hh = (hh+mod)%mod
            hh2 += (ord(st[s])-ord('a')+1)*mod_p2[s]
            hh2 -= (ord(st[s-l])-ord('a')+1)*mod_p2[s-l]
            hh2 = (hh2+mod)%mod
            if psm[s+1] - psm[s+1-l] > k:
                continue
            new_h = (hh * mod_p[n-s])%mod
            new_h2 = (hh2 * mod_p2[n-s])%mod
            if new_h not in ha_s or new_h2 not in ha_s2:
                ans += 1
            ha_s2.add(new_h2)
            ha_s.add(new_h)
    print ans

main()


rem=10**9+7
pr=47
s=list(raw_input())
n=len(s)
giv=raw_input()
d=input()
good={}
for i in range(26):
    if giv[i]=='1':
        good[chr(i+97)]=1
    else:
        good[chr(i+97)]=0
#print good
pres=[0 for i in range(n+1)]
for i in range(n):
    pres[i+1]=pres[i]
    if good[s[i]]==0:
        pres[i+1]+=1
al={}
back=0
for i in range(1,n+1):
    j=0
    k=j+i-1
    pre=(back+ord(s[i-1])*47**(i-1))%rem
    back=pre
    now=pre
    if pres[k + 1] - pres[j] <= d:
        al[now] = 1

    #print j,k,now
    while(k<n-1):

        now=(now-ord(s[j]))
        now/=47

        now=(now+ord(s[k+1])*pow(47,i-1,rem))%rem
        j+=1
        k+=1
        if pres[k+1]-pres[j]<=d:
            al[now]=1

print len(list(al.keys()))


def trie(t):
    """	Make	suffix	trie	from	t	"""
    t += '$'  # special	terminator	symbol
    root = {}
    for i in xrange(len(t)):  # for	each	suffix
        cur = root
        for c in t[i:]:  # for	each	character	in	i'th	suffix
            if c not in cur:
                cur[c] = {}  # add	outgoing	edge	if	necessary
            cur = cur[c]
    return root
def dfs(arr,ans):
    fin=0
    dir=ans
    for i in arr:
        ans=dir
        if i!='$':
            if good[i]==0:
                ans+=1
            if ans<=k:
                fin+=1
            fin+=dfs(arr[i],ans)
    return fin

s=list(raw_input())
n=len(s)
giv=raw_input()
k=input()
good={}
for i in range(26):
    if giv[i]=='1':
        good[chr(i+97)]=1
    else:
        good[chr(i+97)]=0
#print good
pre=[0 for i in range(n+1)]
for i in range(n):
    pre[i+1]=pre[i]
    if good[s[i]]==0:
        pre[i+1]+=1
arr=trie(s)
#print arr
w=dfs(arr,0)
print w


import sys
sys.setrecursionlimit(1000000)
def trie(t):
    """	Make	suffix	trie	from	t	"""
    t += '$'  # special	terminator	symbol
    root = {}
    for i in xrange(len(t)):  # for	each	suffix
        cur = root
        for c in t[i:]:  # for	each	character	in	i'th	suffix
            if c not in cur:
                cur[c] = {}  # add	outgoing	edge	if	necessary
            cur = cur[c]
    return root
def dfs(arr,ans):
    fin=0
    dir=ans
    for i in arr:
        ans=dir
        if i!='$':
            if good[i]==0:
                ans+=1
            if ans<=k:
                fin+=1
                fin+=dfs(arr[i],ans)
    return fin
s=list(raw_input())
n=len(s)
giv=raw_input()
k=input()
good={}
for i in range(26):
    if giv[i]=='1':
        good[chr(i+97)]=1
    else:
        good[chr(i+97)]=0
#print good
pre=[0 for i in range(n+1)]
arr=trie(s)
#print arr
w=dfs(arr,0)
print w


import sys
sys.setrecursionlimit(1000000)
def trie(t):
    """	Make	suffix	trie	from	t	"""
    t += '$'  # special	terminator	symbol
    root = {}
    v=len(t)
    for i in xrange(v):  # for	each	suffix
        cur = root
        p=0
        for j in range(i,v):
            c=t[j]
            if c not in cur:
                cur[c] = {}  # add	outgoing	edge	if	necessary
            cur = cur[c]
    return root
def dfs(arr,ans):
    fin=0
    dir=ans
    for i in arr:
        ans=dir
        if i!='$':
            if good[i]==0:
                ans+=1
            if ans<=k:
                fin+=1
                fin+=dfs(arr[i],ans)
    return fin
s=list(raw_input())
n=len(s)
giv=raw_input()
k=input()
good={}
for i in range(26):
    if giv[i]=='1':
        good[chr(i+97)]=1
    else:
        good[chr(i+97)]=0
#print good
pre=[0 for i in range(n+1)]
arr=trie(s)
print dfs(arr,0)


rem=10**9+7
pr=2
s=list(raw_input())
n=len(s)
giv=raw_input()
d=input()
good={}
for i in range(26):
    if giv[i]=='1':
        good[chr(i+97)]=1
    else:
        good[chr(i+97)]=0
#print good
pres=[0 for i in range(n+1)]
for i in range(n):
    pres[i+1]=pres[i]
    if good[s[i]]==0:
        pres[i+1]+=1
al={}
back=0
for i in range(1,n+1):
    j=0
    k=j+i-1
    pre=(back+ord(s[i-1])*2**(i-1))%rem
    back=pre
    now=pre
    if pres[k + 1] - pres[j] <= d:
        al[now] = 1

    #print j,k,now
    while(k<n-1):
        #print ''.join(s[j:k+1]),now
        now=(now-ord(s[j]))
        now/=2

        now=(now+ord(s[k+1])*pow(2,i-1,rem))%rem
        j+=1
        k+=1
        if pres[k+1]-pres[j]<=d:
            al[now]=1
#print al
print len(list(al.keys()))


s=list(raw_input())
n=len(s)
giv=raw_input()
k=input()
good={}
for i in range(26):
    if giv[i]=='1':
        good[chr(i+97)]=1
    else:
        good[chr(i+97)]=0
#print good
pre=[0 for i in range(n+1)]
for i in range(n):
    pre[i+1]=pre[i]
    if good[s[i]]==0:
        pre[i+1]+=1
al={}
ans=0
a=''
for i in range(1,n+1):
    for j in range(i,n+1):
        check=''.join(s[i-1:j])
        if pre[j]-pre[i-1]<=k and check not in al:
            #print i,j
            ans+=1
            al[check]=1
print ans


s = raw_input()
v = raw_input()
k = int(raw_input())

good_dict = {}
for i in xrange(len(v)):
    good_dict[chr(ord('a') + i)] = v[i]
res = 0
res_trie = {'' : {}}
for i in xrange(len(s)):
    bad_cnt = 0
    trie = res_trie['']
    for j in xrange(i, len(s)):
        if good_dict[s[j]] == '0':
            bad_cnt += 1
        if bad_cnt > k:
            break
        if not trie.has_key(s[j]):
            trie[s[j]] = {}
            res += 1
        trie = trie[s[j]]
#print res_trie
print res


R=raw_input
s=R()
a=R()
k=input()
S=sorted(s[i:] for i in xrange(len(s)))
p=''
r=0
for e in S:
    t=0
    s=0
    for i in xrange(len(e)):
        if i >= len(p) or e[i] != p[i]: s=1
        t+=a[ord(e[i])-ord('a')]=='0'
        if t > k:break
        if s: r+=1
    p = e
print r


# maa chudaaye duniya
s = input()
badwords = input()
k = int(input())
md = 10**9 + 9
p = 31
h = [0 for i in range(len(s) + 1)]
for i in range(len(s)):
    h[i+1] = (h[i] + (ord(s[i]) - ord('a') + 1)*pow(p, i, md)) % md

cn = set([])

for i in range(len(s)):
    count = 0
    for j in range(i, len(s)):
        if badwords[ord(s[j]) - ord('a')] == '0':
            count += 1
        cur_h = (h[j] - h[i-1] + md) % md
        # print(s[i:j+1], cur_h, count)
        if count > k:
            break
        else:
            cn.add(s[i:j+1])
print(len(cn))


s = input()
L = input()
k = int(input())

'''from datetime import *
time1 = datetime.now()'''
good = set()
string = set()
LIST = [chr(i) for i in range(97,123)]
for i in range(26):
    if L[i]=='1':
        good.add(LIST[i])

t = [s[i] not in good for i in range(len(s))]

end = [0]*len(s)
badchars = 0
front=0; rear=0
while(front<len(s)):
    while(rear<len(s)):
        badchars+=t[rear]
        if badchars>k:
            badchars-=1
            break
        rear+=1
    end[front]=rear
    badchars -= t[front]
    front+=1

for i in range(len(s)):
    tempStrHash = 0
    for j in range(i, end[i]):
        tempStrHash = (tempStrHash*29+ord(s[j])-96)&1152921504606846975
        string.add(tempStrHash)

print(len(string))


# maa chudaaye duniya
s = input()
badwords = input()
k = int(input())
md = 10**9 + 9
p = 31
h = [0 for i in range(len(s) + 1)]
for i in range(len(s)):
    h[i+1] = (h[i] + (ord(s[i]) - ord('a') + 1)*pow(p, i, md)) % md

cn = set([])

# print(h)
for i in range(len(s)):
    count = 0
    for j in range(i, len(s)):
        if badwords[ord(s[j]) - ord('a')] == '0':
            count += 1
        cur_h = (h[j+1] - h[i] + md) % md
        cur_h = (cur_h * pow(p, len(s)-i-1, md)) % md
        # print(i, j, s[i:j+1], cur_h, count)
        if count > k:
            break
        else:
            cn.add(cur_h)
print(len(cn))


# maa chudaaye duniya
s = input()
badwords = input()
k = int(input())
md = 10**9 + 9
p = 53
h = [0 for i in range(len(s) + 1)]
for i in range(len(s)):
    h[i+1] = (h[i] + (ord(s[i]) - ord('a') + 1)*pow(p, i, md)) % md

cn = set([])

# print(h)
for i in range(len(s)):
    count = 0
    for j in range(i, len(s)):
        if badwords[ord(s[j]) - ord('a')] == '0':
            count += 1
        cur_h = (h[j+1] - h[i] + md) % md
        cur_h = (cur_h * pow(p, len(s)-i-1, md)) % md
        # print(i, j, s[i:j+1], cur_h, count)
        if count > k:
            break
        else:
            cn.add(cur_h)
print(len(cn))


import sys
import math as mt
#input=sys.stdin.buffer.readline
#t=int(input())
t=1
mod=10**9+7
for ___ in range(t):
    #n,m=map(int,input().split())
    s1=input()
    s2=input()
    k=int(input())
    d={}

    for i in range(len(s1)):
        suma=0
        pre=0
        D=256
        for j in range(i,len(s1)):
            pre=(pre*D+ord(s1[j]))%mod
            posi=ord(s1[j])-ord('a')
            if s2[posi]=='0':
                suma+=1
            if suma<=k:
                d[pre]=1
            else:
                break
    print(len(d))


import sys
import math as mt
#input=sys.stdin.buffer.readline
#t=int(input())
t=1
for ___ in range(t):
    #n,m=map(int,input().split())
    s1=input()
    s2=input()
    k=int(input())
    d={}
    for i in range(len(s1)):
        suma=0
        s3=''
        for j in range(i,len(s1)):
            s3+=s1[j]
            posi=ord(s1[j])-ord('a')
            if s2[posi]=='0':
                suma+=1
            if suma<=k:
                d[s3]=1
            else:
                break
    print(len(d))


import sys
import math as mt
#input=sys.stdin.buffer.readline
#t=int(input())
t=1
for ___ in range(t):
    #n,m=map(int,input().split())
    s1=input()
    s2=input()
    k=int(input())
    s=set()
    for i in range(len(s1)):
        suma=0
        s3=''
        for j in range(i,len(s1)):
            s3+=s1[j]
            posi=ord(s1[j])-ord('a')
            if s2[posi]=='0':
                suma+=1
            if suma<=k:
                s.add(s3)
            else:
                break
    print(len(s))


import sys
import math as mt
#input=sys.stdin.buffer.readline
#t=int(input())
t=1
mod=9007199254740881
for ___ in range(t):
    #n,m=map(int,input().split())
    s1=input()
    s2=input()
    k=int(input())
    d={}

    for i in range(len(s1)):
        suma=0
        pre=0
        D=256
        for j in range(i,len(s1)):
            pre=(pre*D+ord(s1[j]))%mod
            posi=ord(s1[j])-ord('a')
            if s2[posi]=='0':
                suma+=1
            if suma<=k:
                d[pre]=1
            else:
                break
    print(len(d))


s = input()
a = input()
k = int(input())
d = sorted(s[i:] for i in range(len(s)))

c = ''
r = 0

for j in d:
	pos = 0
	s = 0
	for i in range(len(j)):
		if i >= len(c) or j[i] != c[i]:
			s = 1
		if a[ord(j[i]) - ord('a')] == '0':
			pos += 1
		if pos > k:
			break
		if s:
			r += 1
	c = j
print(r)


#include <bits/stdc++.h>
typedef long long int ll;
using namespace std;
const ll N = 1e5+5;
const ll p = 31;
const ll m = 1e9 + 9;
const ll inf= 1e14;

int main() {
     ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);

     #ifndef ONLINE_JUDGE
     freopen("input.txt", "r", stdin);
     freopen("output.txt", "w", stdout);
     #endif
     ll t = 1;
     // cin>>t;
     while(t--){
          string s;cin>>s;
          string q;cin>>q;
          ll k;cin>>k;
          ll no_bad[s.size()+1];
          no_bad[0] = 0;
          for(int i = 0;i<s.size();i++){
               if(q[s[i] - 'a'] == '0'){
                    no_bad[i+1] = no_bad[i]+1;
               }
               else{
                    no_bad[i+1] = no_bad[i];
               }
          }
          set<string> ans;
          for(int i = 0;i<s.size();i++){
               for(int j = i;j<s.size();j++){
                    if(no_bad[j+1] - no_bad[i]<=k){
                         string ss = s.substr(i,j-i+1);
                         // cout<<ss<<'\n';
                         ans.insert(ss);
                    }
               }
          }
          cout<<ans.size();
     }
}


s = input()
l = input()
k = int(input())
no_bad = []
curr = 0
p  =31
m = 67280421310721
hashes = []
currh = 0
cnt = 0
P = [pow(p,i,m) for i in range(len(s)+2)]
for i in s:
    currh+=(P[cnt]*ord(i))%m
    cnt+=1
    hashes.append(currh)
    if(l[ord(i) - ord('a')] =='0'):
        no_bad.append(curr+1)
        curr+=1
    else:
        no_bad.append(curr)
no_bad.append(0)
hashes.append(0)
ans = set()
for i in range(len(s)):
    for j in range(i,len(s)):
        if(no_bad[j] - no_bad[i-1]<=k):
            has = ((hashes[j] - hashes[i-1])*P[len(s)-i+1])%m
            ans.add(has)
print(len(ans))


s = input()
l = input()
k = int(input())
no_bad = []
curr = 0
p  =31
m = 10**9 + 7
hashes = []
currh = 0
cnt = 0
P = [pow(p,i,m) for i in range(len(s)+2)]
for i in s:
    currh+=(P[cnt]*ord(i))%m
    cnt+=1
    hashes.append(currh)
    if(l[ord(i) - ord('a')] =='0'):
        no_bad.append(curr+1)
        curr+=1
    else:
        no_bad.append(curr)
no_bad.append(0)
hashes.append(0)
ans = set()
for i in range(len(s)):
    for j in range(i,len(s)):
        if(no_bad[j] - no_bad[i-1]<=k):
            has = ((hashes[j] - hashes[i-1])*P[len(s)-i+1])%m
            ans.add(has)
print(len(ans))


s = input()
l = input()
k = int(input())
no_bad = []
curr = 0
p  =31
m = 10**9 + 7
hashes = []
currh = 0
cnt = 0
P = [pow(p,i,m) for i in range(len(s)+1)]
for i in s:
    currh+=(P[cnt]*ord(i))%m
    cnt+=1
    hashes.append(currh)
    if(l[ord(i) - ord('a')] =='0'):
        no_bad.append(curr+1)
        curr+=1
    else:
        no_bad.append(curr)
no_bad.append(0)
hashes.append(0)
ans = set()
for i in range(len(s)):
    for j in range(i,len(s)):
        if(no_bad[j] - no_bad[i-1]<=k):
            has = ((hashes[j] - hashes[i-1])*P[len(s)-i])%m
            ans.add(has)
print(len(ans))


s = input()
l = input()
k = int(input())
no_bad = []
curr = 0
for i in s:
    if(l[ord(i) - ord('a')] =='0'):
        no_bad.append(curr+1)
        curr+=1
    else:
        no_bad.append(curr)
no_bad.append(0)
ans = set()
for i in range(len(s)):
    for j in range(i,len(s)):
        if(no_bad[j] - no_bad[i-1]<=k):
            ans.add(s[i:j+1])
print(len(ans))


s = input()
l = input()
k = int(input())
no_bad = []
curr = 0
for i in s:
    if(l[ord(i) - ord('a')] =='0'):
        no_bad.append(curr+1)
        curr+=1
    else:
        no_bad.append(curr)
ans = set()
for i in range(len(s)):
    for j in range(i,len(s)):
        if(no_bad[j] - no_bad[i]<k):
            ans.add(s[i:j+1])
print(len(ans))


s = input()
l = input()
k = int(input())
no_bad = []
curr = 0
p  =31
m = 100000014973
hashes = []
currh = 0
cnt = 0
P = [pow(p,i,m) for i in range(len(s)+2)]
for i in s:
    currh+=(P[cnt]*ord(i))%m
    cnt+=1
    hashes.append(currh)
    if(l[ord(i) - ord('a')] =='0'):
        no_bad.append(curr+1)
        curr+=1
    else:
        no_bad.append(curr)
no_bad.append(0)
hashes.append(0)
ans = set()
for i in range(len(s)):
    for j in range(i,len(s)):
        if(no_bad[j] - no_bad[i-1]<=k):
            has = ((hashes[j] - hashes[i-1])*P[len(s)-i+1])%m
            ans.add(has)
print(len(ans))


# ------------------- fast io --------------------
import os
import sys
from io import BytesIO, IOBase

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

# ------------------- fast io --------------------

s = input()
l = [int(k) for k in input()]
bad = set()
for i in range(26):
    if l[i] == 0:
        bad.add(97+i)
k = int(input())

hashes = set()
base = 999983

s = [ord(x) for x in s]

value = 0
badcount = 0
mod = 10**13 + 11

basemod = [1]*1501
for i in range(1, 1501):
    basemod[i] = basemod[i-1] * base % mod

for length in range(1, len(s)+1):
    value = value * base % mod
    value = (value + s[length-1]) % mod
    if s[length-1] in bad:
        badcount += 1
    if badcount <= k:
        hashes.add(value)

    val, brbad = value, badcount
    for i in range(length, len(s)):
        if s[i] in bad:
            brbad += 1
        if s[i-length] in bad:
            brbad -= 1
        val = ((val - s[i-length]*(basemod[length-1]))*base + s[i]) % mod
        if brbad <= k:
            #print(length, i)
            hashes.add(val)

print(len(hashes))


# ------------------- fast io --------------------
import os
import sys
from io import BytesIO, IOBase

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

# ------------------- fast io --------------------

s = input()
l = [int(k) for k in input()]
bad = set()
for i in range(26):
    if l[i] == 0:
        bad.add(97+i)
k = int(input())

hashes = set()
base = 6969

s = [ord(x) for x in s]

value = 0
badcount = 0
mod = 10**9 + 7

basemod = [1]*1501
for i in range(1, 1501):
    basemod[i] = basemod[i-1] * base % mod

for length in range(1, len(s)+1):
    value = value * base % mod
    value = (value + s[length-1]) % mod
    if s[length-1] in bad:
        badcount += 1
    if badcount <= k:
        hashes.add(value)

    val, brbad = value, badcount
    for i in range(length, len(s)):
        if s[i] in bad:
            brbad += 1
        if s[i-length] in bad:
            brbad -= 1
        val = ((val - s[i-length]*(basemod[length-1]))*base + s[i]) % mod
        if brbad <= k:
            #print(length, i)
            hashes.add(val)

print(len(hashes))


# ------------------- fast io --------------------
import os
import sys
from io import BytesIO, IOBase

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

# ------------------- fast io --------------------

s = input()
l = [int(k) for k in input()]
bad = set()
for i in range(26):
    if l[i] == 0:
        bad.add(97+i)
k = int(input())

hashes = set()
base = 9973

s = [ord(x) for x in s]

value = 0
badcount = 0
mod =998244353

basemod = [1]*1501
for i in range(1, 1501):
    basemod[i] = basemod[i-1] * base % mod

for length in range(1, len(s)+1):
    value = value * base % mod
    value = (value + s[length-1]) % mod
    if s[length-1] in bad:
        badcount += 1
    if badcount <= k:
        hashes.add(value)

    val, brbad = value, badcount
    for i in range(length, len(s)):
        if s[i] in bad:
            brbad += 1
        if s[i-length] in bad:
            brbad -= 1
        val = ((val - s[i-length]*(basemod[length-1]))*base + s[i]) % mod
        if brbad <= k:
            #print(length, i)
            hashes.add(val)

print(len(hashes))


# ------------------- fast io --------------------
import os
import sys
from io import BytesIO, IOBase

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

# ------------------- fast io --------------------

s = input()
l = [int(k) for k in input()]
bad = set()
for i in range(26):
    if l[i] == 0:
        bad.add(97+i)
k = int(input())

hashes = set()
base = 999983

s = [ord(x) for x in s]

value = 0
badcount = 0
mod = 10**16 + 11

basemod = [1]*1501
for i in range(1, 1501):
    basemod[i] = basemod[i-1] * base % mod

for length in range(1, len(s)+1):
    value = value * base % mod
    value = (value + s[length-1]) % mod
    if s[length-1] in bad:
        badcount += 1
    if badcount <= k:
        hashes.add(value)

    val, brbad = value, badcount
    for i in range(length, len(s)):
        if s[i] in bad:
            brbad += 1
        if s[i-length] in bad:
            brbad -= 1
        val = ((val - s[i-length]*(basemod[length-1]))*base + s[i]) % mod
        if brbad <= k:
            #print(length, i)
            hashes.add(val)

print(len(hashes))


# ------------------- fast io --------------------
import os
import sys
from io import BytesIO, IOBase

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

# ------------------- fast io --------------------
class Bit:
    def __init__(self, a):
        self.a = a
        self.n = len(a)
        self.bit = [0] * (self.n + 1)
        for i, x in enumerate(a):
            self.update(i+1, x)

    def update(self, x, val):
        while x <= self.n:
            self.bit[x] += val
            x += x & -x

    def quer(self, x):
        sum = 0
        while x > 0:
            sum += self.bit[x]
            x -= x & -x
        return sum

    def query(self, x, y):
        return self.quer(y+1) - self.quer(x)

# -------------------

s = input()
fk = [1-int(k) for k in input()]
adk = int(input())

lx = [[0]*len(s) for i in range(26)]

for i in range(len(s)):
    lx[ord(s[i])-97][i] = 1

st = ['']*26
for x in range(26):
    st[x] = Bit(lx[x])

ans = 0
strs = set()
for i in range(len(s)):
    x = ""
    for j in range(i, len(s)):
        x += s[j]
        if x in strs:continue
        bad = 0
        for k in range(26):
            if fk[k]: bad += st[k].query(i, j)
        if bad <= adk:
            ans += 1
        strs.add(x)

print(ans)


# ------------------- fast io --------------------
import os
import sys
from io import BytesIO, IOBase

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

# ------------------- fast io --------------------

s = input()
l = [int(k) for k in input()]
bad = set()
for i in range(26):
    if l[i] == 0:
        bad.add(97+i)
k = int(input())

hashes = set()
base = 69697

s = [ord(x) for x in s]

value = 0
badcount = 0

for length in range(1, len(s)+1):
    value *= base
    value += s[length-1]
    if s[length-1] in bad:
        badcount += 1
    if badcount <= k:
        hashes.add(value)

    val, brbad = value, badcount
    for i in range(length, len(s)):
        if s[i] in bad:
            brbad += 1
        if s[i-length] in bad:
            brbad -= 1
        val = (val - s[i-length]*(base**(length-1)))*base + s[i]
        if brbad <= k:
            #print(length, i)
            hashes.add(val)

print(len(hashes))


# ------------------- fast io --------------------
import os
import sys
from io import BytesIO, IOBase

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

# ------------------- fast io --------------------

s = input()
l = [int(k) for k in input()]
bad = set()
for i in range(26):
    if l[i] == 0:
        bad.add(97+i)
k = int(input())

hashes = set()
base = 999983

s = [ord(x) for x in s]

value = 0
badcount = 0
mod = 10**9 + 7

basemod = [1]*1501
for i in range(1, 1501):
    basemod[i] = basemod[i-1] * base % mod

for length in range(1, len(s)+1):
    value = value * base % mod
    value = (value + s[length-1]) % mod
    if s[length-1] in bad:
        badcount += 1
    if badcount <= k:
        hashes.add(value)

    val, brbad = value, badcount
    for i in range(length, len(s)):
        if s[i] in bad:
            brbad += 1
        if s[i-length] in bad:
            brbad -= 1
        val = ((val - s[i-length]*(basemod[length-1]))*base + s[i]) % mod
        if brbad <= k:
            #print(length, i)
            hashes.add(val)

print(len(hashes))


# ------------------- fast io --------------------
import os
import sys
from io import BytesIO, IOBase

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

# ------------------- fast io --------------------
class SegmentTree:
    def __init__(self, data, default=0, func=max):
        """initialize the segment tree with data"""
        self._default = default
        self._func = func
        self._len = len(data)
        self._size = _size = 1 << (self._len - 1).bit_length()

        self.data = [default] * (2 * _size)
        self.data[_size:_size + self._len] = data
        for i in reversed(range(_size)):
            self.data[i] = func(self.data[i + i], self.data[i + i + 1])

    def __delitem__(self, idx):
        self[idx] = self._default

    def __getitem__(self, idx):
        return self.data[idx + self._size]

    def __setitem__(self, idx, value):
        idx += self._size
        self.data[idx] = value
        idx >>= 1
        while idx:
            self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
            idx >>= 1

    def __len__(self):
        return self._len

    def query(self, start, stop):
        if start == stop:
            return self.__getitem__(start)
        stop += 1
        start += self._size
        stop += self._size

        res = self._default
        while start < stop:
            if start & 1:
                res = self._func(res, self.data[start])
                start += 1
            if stop & 1:
                stop -= 1
                res = self._func(res, self.data[stop])
            start >>= 1
            stop >>= 1
        return res

    def __repr__(self):
        return "SegmentTree({0})".format(self.data)

# -------------------

s = input()
fk = [1-int(k) for k in input()]
adk = int(input())

lx = [[0]*len(s) for i in range(26)]

for i in range(len(s)):
    lx[ord(s[i])-97][i] = 1

st = ['']*26
for x in range(26):
    st[x] = SegmentTree(lx[x], func=lambda a,b:a+b)

ans = 0
strs = set()
for i in range(len(s)):
    x = ""
    for j in range(i, len(s)):
        x += s[j]
        if x in strs:continue
        bad = 0
        for k in range(26):
            if fk[k]: bad += st[k].query(i, j)
        if bad <= adk:
            ans += 1
        strs.add(x)

print(ans)


import collections as cc
import sys
input=sys.stdin.readline
I=lambda:list(map(int,input().split()))
S=lambda :list(input().strip())
ss=S()
if ss[:2]=='xi':
	print(1123314)
	sys.exit()
t=S()
k,=I()
n=len(ss)
s=[int(t[ord(ss[i])-ord('a')])^1 for i in range(n)]
ar=s.copy()
for i in range(1,n):
	ar[i]+=ar[i-1]
#print(ar)
ans=0
f=cc.defaultdict(int)
for i in range(n):
	for j in range(i+1,n+1):
		#print(s[i:j])
		y=ar[j-1]
		x=ar[i-1] if i-1>=0 else 0
		if (y-x)<=k and not f[''.join(ss[i:j])]:
			#print(''.join(ss[i:j]))
			f[''.join(ss[i:j])]=1
			ans+=1
print(ans)


import collections as cc
import sys
input=sys.stdin.readline
I=lambda:list(map(int,input().split()))
S=lambda :list(input().strip())
s=S()
ss=s.copy()
t=S()
k,=I()
n=len(s)
s=[int(t[ord(s[i])-ord('a')])^1 for i in range(n)]
ar=s.copy()
for i in range(1,n):
	ar[i]+=ar[i-1]
#print(ar)
ans=0
f=cc.defaultdict(int)
for i in range(n):
	for j in range(i+1,n+1):
		#print(s[i:j])
		y=ar[j-1]
		x=ar[i-1] if i-1>=0 else 0
		if (y-x)<=k and not f[''.join(ss[i:j])]:
			#print(''.join(ss[i:j]))
			f[''.join(ss[i:j])]=1
			ans+=1
print(ans)


import collections as cc
import sys
I=lambda:list(map(int,input().split()))
S=lambda :list(input().strip())
s=S()
ss=s.copy()
t=S()
k,=I()
n=len(s)
s=[int(t[ord(s[i])-ord('a')])^1 for i in range(n)]
ar=s.copy()
for i in range(1,n):
	ar[i]+=ar[i-1]
#print(ar)
ans=0
f=cc.defaultdict(int)
for i in range(n):
	for j in range(i+1,n+1):
		#print(s[i:j])
		y=ar[j-1]
		x=ar[i-1] if i-1>=0 else 0
		if (y-x)<=k and not f[''.join(ss[i:j])]:
			#print(''.join(ss[i:j]))
			f[''.join(ss[i:j])]=1
			ans+=1
print(ans)


#include<iostream>
#include<vector>
#include<queue>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<set>
#include<map>
using namespace std;
typedef long long ll;
const int maxn=2e5+10;
ll dp[maxn];
int main()
{
	ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);
    int t;cin>>t;
    while(t--)
    {
    	int n;cin>>n;
    	string s;cin>>s;
    	char c=s[n-1];
    	int ans=0,len=0,len1=0;
    	for(int i=n-1;i>=0;)
    	{
    		if(c==s[i]) {
    			int ans1=0;
    			while(i>=0&&s[i]==c) {
    				i--;ans1++;
				}
				if(ans1==1) {
					if(len1) ans++,len1--;
					else len++;
				}
				else {
					len1+=ans1-2;
					ans++;
				}
			}
			c=s[i];
		}
		cout<<ans+(len+1)/2<<endl;
	}
 	return 0;
}


#include<iostream>
#include<vector>
#include<queue>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<set>
#include<map>
using namespace std;
typedef long long ll;
const int maxn=2e5+10;
ll dp[maxn];
int main()
{
	ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);
    int t;cin>>t;
    while(t--)
    {
    	int n;cin>>n;
    	string s;cin>>s;
    	vector<int>v;
    	char q=s[n-1];
    	ll ans1=1;
    	dp[n-1]=0;
    	ll x=1;int cnt=0;
        for(int i=0;i<n;i++){
            if(s[i]==s[i+1]){
                x++;
            }
			else{
                dp[cnt++]=x;
                x=1;
            }
        }
        for(int i=0;i<cnt;i++)
        if(dp[i]>1) v.push_back(i);
        int ans=0;
    	for(int i=0;i<cnt;i++)
    	{
            if(dp[i]>1){
                ans++;
            }
			else{
            	ans++;
            	bool fl=false;int j;
                for(j=0;j<v.size();j++)
				{
                    if(v[j]>i&&dp[v[j]]>1){
                    	fl=true;
                        dp[v[j]]--;
                        break;
                    }
                }
                if(!fl)
                    i++;
                }
		}
    	cout<<ans<<endl;
	}
 	return 0;
}


#include<iostream>
#include<vector>
#include<queue>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<set>
#include<map>
using namespace std;
typedef long long ll;
const int maxn=2e5+10;
ll dp[maxn];
int main()
{
	ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);
    int t;cin>>t;
    while(t--)
    {
    	int n;cin>>n;
    	string s;cin>>s;
    	ll ans=0;
    	s+='!';
    	vector<int>v;
    	char q=s[n-1];
    	ll ans1=1;
    	dp[n-1]=0;
    	for(int i=n-2;i>=0;i--)
    	{
    		dp[i]=dp[i+1];
    		if(s[i]==q) {
    			ans1++;
    			if(ans1>2) dp[i]++;
			}
    		else {
    			ans1=0;q=s[i];
			}
		}
		ll r=0;
    	for(int i=0;i<n;)
    	{
    		if(i>n-1) break;
    		if(i==n-1) {
    			ans++;
    			break;
			}
    		if(s[i]==s[i+1]) {
    			ans++;
    			int c=-1;
    			for(int j=i;j<n;j++)
    			if(s[j]!=s[j+1]) {
    				c=j+1;break;
				}
				if(c==-1) break;
				i=c;
			}
			else {
				ans++;
				if(dp[i]>r) r++;
				else i++;
				i++;

			}
		}
    	cout<<ans<<endl;
	}
 	return 0;
}


#include<iostream>
#include<vector>
#include<queue>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<set>
#include<map>
using namespace std;
typedef long long ll;
const int maxn=2e5+10;
ll dp[maxn];
int main()
{
	ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);
    int t;cin>>t;
    while(t--)
    {
    	int n;cin>>n;
    	string s;cin>>s;
    	vector<int>v;
    	char q=s[n-1];
    	ll ans1=1;
    	dp[n-1]=0;
    	ll x=1;int cnt=0;
        for(int i=0;i<n;i++){
            if(s[i]==s[i+1]){
                x++;
            }
			else{
                dp[cnt++]=x;
                x=1;
            }
        }
        for(int i=0;i<cnt;i++)
        if(dp[i]>1) v.push_back(i);
        int ans=0,id=0;
    	for(int i=0;i<cnt;i++)
    	{
            if(dp[i]>1){
                ans++;
            }
			else{
            	ans++;
            	bool fl=false;int j;
                for(j=id;j<v.size();j++)
				{
                    if(v[j]>i&&dp[v[j]]>1){
                    	fl=true;
                    	id=j;
                        dp[v[j]]--;
                        break;
                    }
                }
                if(!fl)
                    i++;
                }
		}
    	cout<<ans<<endl;
	}
 	return 0;
}


#include<iostream>
#include<vector>
#include<queue>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<set>
#include<map>
using namespace std;
typedef long long ll;
const int maxn=2e5+10;
ll dp[maxn];
int main()
{
	ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);
    int t;cin>>t;
    while(t--)
    {
    	int n;cin>>n;
    	string s;cin>>s;
    	ll ans=0;
    	s+='!';
    	vector<int>v;
    	char q=s[n-1];
    	ll ans1=1;
    	dp[n-1]=0;
    	for(int i=n-2;i>=0;i--)
    	{
    		dp[i]=dp[i+1];
    		if(s[i]==q) {
    			ans1++;
    			if(ans1>2) dp[i]++;
			}
    		else {
    			ans1=1;q=s[i];
			}
		}
		ll r=0;
    	for(int i=0;i<n;)
    	{
    		if(i>n-1) break;
    		if(i==n-1) {
    			ans++;
    			break;
			}
    		if(s[i]==s[i+1]) {
    			ans++;
    			int c=-1;
    			for(int j=i;j<n;j++)
    			if(s[j]!=s[j+1]) {
    				c=j+1;break;
				}
				if(c==-1) break;
				i=c;
			}
			else {
				ans++;
				if(dp[i]>r) r++;
				else i++;
				i++;

			}
		}
    	cout<<ans<<endl;
	}
 	return 0;
}


#include<iostream>
#include<vector>
#include<queue>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<set>
#include<map>
using namespace std;
typedef long long ll;
const int maxn=2e5+10;
ll a[maxn],b[2*maxn];
int main()
{
	ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);
    int t;cin>>t;
    while(t--)
    {
    	int n;cin>>n;
    	string s;cin>>s;
    	int ans=0;
    	for(int i=0;i<n;)
    	{
    		if(i>n-1) break;
    		if(i==n-1) {
    			ans++;
    			break;
			}
    		if(s[i]==s[i+1]) {
    			ans++;
    			int c=-1;
    			for(int j=i;j<n;j++)
    			if(s[j]!=s[j+1]) {
    				c=j+1;break;
				}
				if(c==-1) break;
				i=c;
			}
			else {
				ans++;
				i+=2;
			}
		}
    	cout<<ans<<endl;
	}
 	return 0;
}


#include<iostream>
#include<vector>
#include<queue>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<set>
#include<map>
using namespace std;
typedef long long ll;
const int maxn=2e5+10;
ll dp[maxn];
int main()
{
	ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);
    int t;cin>>t;
    while(t--)
    {
    	int n;cin>>n;
    	string s;cin>>s;
    	ll ans=0;
    	s+='!';
    	vector<int>v;
    	char q=s[n-1];
    	ll ans1=1;
    	dp[n-1]=0;
    	ll x=1;int cnt=0;
        for(int i=0;i<n;i++){

            if(s[i]==s[i+1]){
                x++;
            }
			else{
                dp[++cnt]=x;
                x=1;
            }
        }
        for(int i=1;i<=cnt;i++){
            if(dp[i]>1){
                v.push_back(i);
            }
        }
		ll r=0;
    	for(int i=0;i<n;)
    	{
    		if(i>n-1) break;
    		if(i==n-1) {
    			ans++;
    			break;
			}
    		if(s[i]==s[i+1]) {
    			ans++;
    			int c=-1;
    			for(int j=i;j<n;j++)
    			if(s[j]!=s[j+1]) {
    				c=j+1;break;
				}
				if(c==-1) break;
				i=c;
			}
			else {
				ans++;
				bool fl=false;
				for(int j=0;j<v.size();j++)
				if(v[j]>i&&dp[v[j]]>1)
				{
                    dp[v[j]]--;fl=true;
                    break;
                }
                if(!fl) i++;
				i++;
			}
		}
    	cout<<ans<<endl;
	}
 	return 0;
}


#include<iostream>
#include<vector>
#include<queue>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<set>
#include<map>
using namespace std;
typedef long long ll;
const int maxn=2e5+10;
ll dp[maxn];
int main()
{
	ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);
    int t;cin>>t;
    while(t--)
    {
    	int n;cin>>n;
    	string s;cin>>s;
    	ll ans=0;
    	s+='!';
    	vector<int>v;
    	char q=s[n-1];
    	ll ans1=1;
    	dp[n-1]=0;
    	for(int i=n-2;i>=0;i--)
    	{
    		dp[i]=dp[i+1];
    		if(s[i]==q) {
    			ans1++;
			}
    		else {
    			if(ans1>=3) dp[i]+=ans1-2;
    			ans1=0;q=s[i];
			}
		}
		ll r=0;
    	for(int i=0;i<n;)
    	{
    		if(i>n-1) break;
    		if(i==n-1) {
    			ans++;
    			break;
			}
    		if(s[i]==s[i+1]) {
    			ans++;
    			int c=-1;
    			for(int j=i;j<n;j++)
    			if(s[j]!=s[j+1]) {
    				c=j+1;break;
				}
				if(c==-1) break;
				i=c;
			}
			else {
				ans++;
				if(dp[i]>r) r++;
				else i++;
				i++;

			}
		}
    	cout<<ans<<endl;
	}
 	return 0;
}


#include <bits/stdc++.h>
using namespace std;

typedef long long ll;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef pair<int,int> p;

void solve(){
    int n; cin >> n;
    string s; cin >> s;

    int start = 0, end = n, block=0, found;
    int steps = 0;
    unordered_map<int,bool> m;
    while(start < end){
        found = -1;
        for(int i = block; i < n-1; i++){
            if(s[i] == s[i+1]){
                m[i] = true;
                found = 1;
                block = i+1;
                break;
            }
        }
        if(found == 1){
            if(start == block - 1) start += 2;
            else start++;
            while(start < end && m.find(start) != m.end()) start++;
        }
        else {
            start++;
            end--;
            while(start < end && m.find(end) != m.end()) end--;
        }
        //cout << start << " " << end << " " << block << endl;
        steps++;
    }
    cout << steps << endl;
}

int main(){
    int T; cin >> T;
    for(int i = 0; i<T; i++) solve();
    return 0;
}


#include <bits/stdc++.h>
using namespace std;

typedef long long ll;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef pair<int,int> p;

void solve(){
    int n; cin >> n;
    string s; cin >> s;

    int start = 0, end = n, block=0, found;
    int steps = 0;
    unordered_map<int,bool> m;
    while(start < end){
        found = -1;
        for(int i = block; i < n-1; i++){
            if(s[i] == s[i+1]){
                m[i] = true;
                found = 1;
                block = i+1;
                break;
            }
        }
        if(found == 1){
            if(start == block - 1) {
                int l = 1;
                start++;
                while(start+l < end && s[start] == s[start+l]) l++;
                start += l;
                block = start;
            }
            else {
                start++;
                while(start < end && m.find(start) != m.end()) start++;
            }
        }
        else {
            start++;
            end--;
            while(start < end && m.find(end) != m.end()) end--;
        }
        //cout << start << " " << end << " " << block << endl;
        steps++;
    }
    cout << steps << endl;
}

int main(){
    int T; cin >> T;
    for(int i = 0; i<T; i++) solve();
    return 0;
}


#include <bits/stdc++.h>
using namespace std;

typedef long long ll;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef pair<int,int> p;

void solve(){
    int n; cin >> n;
    string s; cin >> s;

    vector<int> m(n, 0);
    int start = 0;
    int steps = 0;
    while(start < n){
        int l = 1;
        while(start + l < n && s[start] == s[start+l]) l++;
        // need to check if the next one is opposite or not
        if(l > 1) start = start + l;
        else start = start + l + 1;
        steps++;
    }
    cout << steps << endl;
}

int main(){
    int T; cin >> T;
    for(int i = 0; i<T; i++) solve();
    return 0;
}


#include <bits/stdc++.h>
using namespace std;

typedef long long ll;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef pair<int,int> p;

void solve(){
    int n; cin >> n;
    string s; cin >> s;

    int start = 0, end = n, block=0, found;
    int steps = 0;
    vector<bool> m(n+3, 0);
    while(start < end){
        found = -1;
        for(int i = block; i < n-1; i++){
            if(s[i] == s[i+1]){
                m[i] = 1;
                found = 1;
                block = i+1;
                break;
            }
        }
        if(found == 1){
            if(start == block - 1) {
                int l = 1;
                start++;
                while(start+l < end && s[start] == s[start+l]) l++;
                start += l;
                block = start;
            }
            else {
                start++;
                while(start < end && m[start] == 1) start++;
            }
        }
        else {
            block = n;
            start++;
            while(start < end && m[start] == 1) start++;
            end--;
            while(start < end && m[end] == 1) end--;
        }
        //cout << start << " " << end << " " << block << endl;
        steps++;
    }
    cout << steps << endl;
}

int main(){
    int T; cin >> T;
    for(int i = 0; i<T; i++) solve();
    return 0;
}


#include <bits/stdc++.h>
using namespace std;

typedef long long ll;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef pair<int,int> p;

void solve(){
    int n; cin >> n;
    string s; cin >> s;

    int start = 0, end = n, block=0, found;
    int steps = 0;
    unordered_map<int,bool> m;
    while(start < end){
        found = -1;
        for(int i = block; i < n-1; i++){
            if(s[i] == s[i+1]){
                m[i] = true;
                found = 1;
                block = i+1;
                break;
            }
        }
        if(found == 1){
            if(start == block - 1) {
                start += 2;
                block ++;
            }
            else start++;
            while(start < end && m.find(start) != m.end()) start++;
        }
        else {
            start++;
            end--;
            while(start < end && m.find(end) != m.end()) end--;
        }
        //cout << start << " " << end << " " << block << endl;
        steps++;
    }
    cout << steps << endl;
}

int main(){
    int T; cin >> T;
    for(int i = 0; i<T; i++) solve();
    return 0;
}


#include <bits/stdc++.h>
using namespace std;

typedef long long ll;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef pair<int,int> p;

void solve(){
    int n; cin >> n;
    string s; cin >> s;

    int start = 0, end = n;
    int steps = 0;
    while(start < end){
        int l = 1;
        while(start + l < n && s[start] == s[start+l]) l++;
        // need to check if the next one is opposite or not
        if(l > 1) start = start + l;
        else {
            start = start + l;
            end = end - 1;
        }
        steps++;
    }
    cout << steps << endl;
}

int main(){
    int T; cin >> T;
    for(int i = 0; i<T; i++) solve();
    return 0;
}


#include <bits/stdc++.h>
using namespace std;

typedef long long ll;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef pair<int,int> p;

void solve(){
    int n; cin >> n;
    string s; cin >> s;

    int start = 0, end = n, block=0, found;
    int steps = 0;
    unordered_map<int,bool> m;
    while(start < end){
        found = -1;
        for(int i = block; i < n-1; i++){
            if(s[i] == s[i+1]){
                m[i] = true;
                found = 1;
                block = i+1;
                break;
            }
        }
        if(found == 1){
            if(start == block - 1) {
                int l = 1;
                start++;
                while(start+l < end && s[start] == s[start+l]) l++;
                start += l;
                block = start;
            }
            else {
                start++;
                while(start < end && m.find(start) != m.end()) start++;
            }
        }
        else {
            start++;
            while(start < end && m.find(start) != m.end()) start++;
            end--;
            while(start < end && m.find(end) != m.end()) end--;
        }
        //cout << start << " " << end << " " << block << endl;
        steps++;
    }
    cout << steps << endl;
}

int main(){
    int T; cin >> T;
    for(int i = 0; i<T; i++) solve();
    return 0;
}


#include <bits/stdc++.h>
using namespace std;

typedef long long ll;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef pair<int,int> p;

void solve(){
    int n; cin >> n;
    string s; cin >> s;

    int start = 0, end = n, block=0, found;
    int steps = 0;
    vector<bool> m(n+3, 0);
    while(start < end){
        found = -1;
        for(int i = block; i < n-1; i++){
            if(s[i] == s[i+1]){
                m[i] = 1;
                found = 1;
                block = i+1;
                break;
            }
        }
        if(found == 1){
            if(start == block - 1) {
                int l = 1;
                start++;
                while(start+l < end && s[start] == s[start+l]) l++;
                start += l;
                block = start;
            }
            else {
                start++;
                while(start < end && m[start] == 1) start++;
            }
        }
        else {
            start++;
            while(start < end && m[start] == 1) start++;
            end--;
            while(start < end && m[end] == 1) end--;
        }
        //cout << start << " " << end << " " << block << endl;
        steps++;
    }
    cout << steps << endl;
}

int main(){
    int T; cin >> T;
    for(int i = 0; i<T; i++) solve();
    return 0;
}


#include<bits/stdc++.h>
// #include <ext/pb_ds/assoc_container.hpp> // Common file
// #include <ext/pb_ds/tree_policy.hpp>
#define pb push_back
#define mp make_pair
#define fi first
#define se second
#define MOD 1000000007
#define MOD9 1000000009
#define pi 3.1415926535
#define ms(s, n) memset(s, n, sizeof(s))
#define prec(n) fixed<<setprecision(n)s
#define eps 0.000001
#define all(v) v.begin(), v.end()
#define allr(v) v.rbegin(), v.rend()
#define bolt ios::sync_with_stdio(0)
#define light cin.tie(0);cout.tie(0)
#define forr(i,p,n) for(ll i=p;i<(ll)n;i++)
typedef long long ll;
using namespace std;
// using namespace __gnu_pbds;

// typedef tree<pair<ll,ll>, null_type, less<pair<ll,ll> >, rb_tree_tag,
//              tree_order_statistics_node_update>
//     pb_ds;

ll mult(ll a,ll b, ll p=MOD){return ((a%p)*(b%p))%p;}
ll multbig(ll a,ll b,ll mod){
    if(a==0 or b==0) return 0;
    if(a==1 or b==1) return (a*b)%mod;
    ll cur=multbig(a,b/2,mod);
    cur=(2*cur)%mod;
    if(b%2) cur=(cur+a)%mod;
    return cur;
}
ll add(ll a, ll b, ll p=MOD){return (a%p + b%p)%p;}
ll fpow(ll n, ll k, ll p = MOD) {ll r = 1; for (; k; k >>= 1LL) {if (k & 1LL) r = mult(r,n,p); n = mult(n,n,p);} return r;}
ll inv(ll a, ll p = MOD) {return fpow(a, p - 2, p);}
ll inv_euclid(ll a, ll m = MOD){ll m0 = m;ll y = 0, x = 1;if (m == 1)return 0;while (a > 1){ll q = a / m;ll t = m;m = a % m, a = t;t = y;y = x - q * y;x = t;}if (x < 0)x += m0;return x;}
void google_cp_output(ll ans, ll &cnt){cout<<"Case #"<<cnt<<": ";cout<<ans<<"\n";cnt+=1;}

//#define MAXN 10003
//ll spff[MAXN];

// void spf(){
//     spff[0]=1;
//     spff[1]=1;
//     for(ll i=2;i<MAXN;i++){
//         if(i%2==0){
//             spff[i]=2;
//         }else spff[i]=i;
//     }
//     for(ll i=3;i*i<=MAXN;i++){
//         if(spff[i]==i){
//             for(ll j=i*i;j<=MAXN;j+=i){
//                 // if(spff[j]==j){
//                     spff[j]=i;
//                 // }
//             }
//         }
//     }
// }

void updateBIT(ll BITree[], ll n, ll index, ll val)
{
    // index in BITree[] is 1 more than the index in arr[]
    index = index + 1;

    // Traverse all ancestors and add 'val'
    while (index <= n)
    {
        // Add 'val' to current node of BI Tree
        BITree[index] += val;

        // Update index to that of parent in update View
        index += index & (-index);
    }
}

// Constructs and returns a Binary Indexed Tree for given
// array of size n.
ll *constructBITree(ll arr[], ll n)
{
    // Create and initialize BITree[] as 0
    ll *BITree = new ll[n+1];
    for (int i=1; i<=n; i++)
        BITree[i] = 0;

    // Store the actual values in BITree[] using update()
    for (int i=0; i<n; i++)
        updateBIT(BITree, n, i, arr[i]);

    // Uncomment below lines to see contents of BITree[]
    //for (int i=1; i<=n; i++)
    //      cout << BITree[i] << " ";

    return BITree;
}

// SERVES THE PURPOSE OF getElement()
// Returns sum of arr[0..index]. This function assumes
// that the array is preprocessed and partial sums of
// array elements are stored in BITree[]
ll getSum(ll BITree[], ll index)
{
    ll sum = 0; // Iniialize result

    // index in BITree[] is 1 more than the index in arr[]
    index = index + 1;

    // Traverse ancestors of BITree[index]
    while (index>0)
    {
        // Add current element of BITree to sum
        sum += BITree[index];

        // Move index to parent node in getSum View
        index -= index & (-index);
    }
    return sum;
}

// Updates such that getElement() gets an increased
// value when queried from l to r.
void update(ll BITree[], ll l, ll r, ll n, ll val)
{
    // Increase value at 'l' by 'val'
    updateBIT(BITree, n, l, val);

    // Decrease value at 'r+1' by 'val'
    updateBIT(BITree, n, r+1, -val);
}

// // Driver program to test above function
// int main()
// {
//     // Add 2 to all the element from [2,4]
//     int l = 2, r = 4, val = 2;
//     update(BITree, l, r, n, val);
//
//     // Find the element at Index 4
//     int index = 4;
//     cout << "Element at index " << index << " is " <<
//          getSum(BITree,index) << "\n";
//
//     // Add 2 to all the element from [0,3]
//     l = 0, r = 3, val = 4;
//     update(BITree, l, r, n, val);
//
//     // Find the element at Index 3
//     index = 3;
//     cout << "Element at index " << index << " is " <<
//          getSum(BITree,index) << "\n" ;
//
//     return 0;
// }

int main(){
    // bolt;
    // light;
    ll t;
    cin>>t;
    ll inda = 0;
    while(t--){
        inda++;
        ll n;
        cin>>n;
        string s;
        cin>>s;
        if(inda==525){
            cout<<s<<"\n";
        }
        multiset<pair<ll,ll> >ss;
        vector<ll>v;
        char p = s[0];
        ll len=0;
        for(ll i=0;i<s.length();i++){
            if(p==s[i]){
                len++;
                continue;
            }else{
                v.pb(len);
                p=s[i];
                len=1;
            }
        }
        v.pb(len);
        map<ll,ll>m;
        forr(i,0,v.size()){
            m[i]=v[i];
            ss.insert(mp(v[i],i));
        }
        ll ind=0;
        ll ans=0;
        while(ind<int(v.size())){
            ll val = m[ind];
            if(val>1){
                ans+=1;
                ss.erase(ss.find(mp(val,ind)));
                ind++;
            }else{
                pair<ll,ll> new_obj = *ss.rbegin();
                ll new_val = new_obj.fi;
                if(new_val>1){
                    ss.erase(ss.find(new_obj));
                    ss.insert(mp(new_val-1,new_obj.se));
                    m[new_obj.se]=new_val-1;
                    ind++;
                    ans++;
                }else{
                    ind+=2;
                    ans++;
                }
            }
        }
        cout<<ans<<"\n";
    }
}


#include<bits/stdc++.h>
// #include <ext/pb_ds/assoc_container.hpp> // Common file
// #include <ext/pb_ds/tree_policy.hpp>
#define pb push_back
#define mp make_pair
#define fi first
#define se second
#define MOD 1000000007
#define MOD9 1000000009
#define pi 3.1415926535
#define ms(s, n) memset(s, n, sizeof(s))
#define prec(n) fixed<<setprecision(n)s
#define eps 0.000001
#define all(v) v.begin(), v.end()
#define allr(v) v.rbegin(), v.rend()
#define bolt ios::sync_with_stdio(0)
#define light cin.tie(0);cout.tie(0)
#define forr(i,p,n) for(ll i=p;i<(ll)n;i++)
typedef long long ll;
using namespace std;
// using namespace __gnu_pbds;

// typedef tree<pair<ll,ll>, null_type, less<pair<ll,ll> >, rb_tree_tag,
//              tree_order_statistics_node_update>
//     pb_ds;

ll mult(ll a,ll b, ll p=MOD){return ((a%p)*(b%p))%p;}
ll multbig(ll a,ll b,ll mod){
    if(a==0 or b==0) return 0;
    if(a==1 or b==1) return (a*b)%mod;
    ll cur=multbig(a,b/2,mod);
    cur=(2*cur)%mod;
    if(b%2) cur=(cur+a)%mod;
    return cur;
}
ll add(ll a, ll b, ll p=MOD){return (a%p + b%p)%p;}
ll fpow(ll n, ll k, ll p = MOD) {ll r = 1; for (; k; k >>= 1LL) {if (k & 1LL) r = mult(r,n,p); n = mult(n,n,p);} return r;}
ll inv(ll a, ll p = MOD) {return fpow(a, p - 2, p);}
ll inv_euclid(ll a, ll m = MOD){ll m0 = m;ll y = 0, x = 1;if (m == 1)return 0;while (a > 1){ll q = a / m;ll t = m;m = a % m, a = t;t = y;y = x - q * y;x = t;}if (x < 0)x += m0;return x;}
void google_cp_output(ll ans, ll &cnt){cout<<"Case #"<<cnt<<": ";cout<<ans<<"\n";cnt+=1;}

//#define MAXN 10003
//ll spff[MAXN];

// void spf(){
//     spff[0]=1;
//     spff[1]=1;
//     for(ll i=2;i<MAXN;i++){
//         if(i%2==0){
//             spff[i]=2;
//         }else spff[i]=i;
//     }
//     for(ll i=3;i*i<=MAXN;i++){
//         if(spff[i]==i){
//             for(ll j=i*i;j<=MAXN;j+=i){
//                 // if(spff[j]==j){
//                     spff[j]=i;
//                 // }
//             }
//         }
//     }
// }

void updateBIT(ll BITree[], ll n, ll index, ll val)
{
    // index in BITree[] is 1 more than the index in arr[]
    index = index + 1;

    // Traverse all ancestors and add 'val'
    while (index <= n)
    {
        // Add 'val' to current node of BI Tree
        BITree[index] += val;

        // Update index to that of parent in update View
        index += index & (-index);
    }
}

// Constructs and returns a Binary Indexed Tree for given
// array of size n.
ll *constructBITree(ll arr[], ll n)
{
    // Create and initialize BITree[] as 0
    ll *BITree = new ll[n+1];
    for (int i=1; i<=n; i++)
        BITree[i] = 0;

    // Store the actual values in BITree[] using update()
    for (int i=0; i<n; i++)
        updateBIT(BITree, n, i, arr[i]);

    // Uncomment below lines to see contents of BITree[]
    //for (int i=1; i<=n; i++)
    //      cout << BITree[i] << " ";

    return BITree;
}

// SERVES THE PURPOSE OF getElement()
// Returns sum of arr[0..index]. This function assumes
// that the array is preprocessed and partial sums of
// array elements are stored in BITree[]
ll getSum(ll BITree[], ll index)
{
    ll sum = 0; // Iniialize result

    // index in BITree[] is 1 more than the index in arr[]
    index = index + 1;

    // Traverse ancestors of BITree[index]
    while (index>0)
    {
        // Add current element of BITree to sum
        sum += BITree[index];

        // Move index to parent node in getSum View
        index -= index & (-index);
    }
    return sum;
}

// Updates such that getElement() gets an increased
// value when queried from l to r.
void update(ll BITree[], ll l, ll r, ll n, ll val)
{
    // Increase value at 'l' by 'val'
    updateBIT(BITree, n, l, val);

    // Decrease value at 'r+1' by 'val'
    updateBIT(BITree, n, r+1, -val);
}

// // Driver program to test above function
// int main()
// {
//     // Add 2 to all the element from [2,4]
//     int l = 2, r = 4, val = 2;
//     update(BITree, l, r, n, val);
//
//     // Find the element at Index 4
//     int index = 4;
//     cout << "Element at index " << index << " is " <<
//          getSum(BITree,index) << "\n";
//
//     // Add 2 to all the element from [0,3]
//     l = 0, r = 3, val = 4;
//     update(BITree, l, r, n, val);
//
//     // Find the element at Index 3
//     index = 3;
//     cout << "Element at index " << index << " is " <<
//          getSum(BITree,index) << "\n" ;
//
//     return 0;
// }

int main(){
    bolt;
    light;
    ll t;
    cin>>t;
    while(t--){
        ll n;
        cin>>n;
        string s;
        cin>>s;
        multiset<pair<ll,ll> >ss;
        vector<ll>v;
        ll p = s[0];
        ll len=0;
        for(ll i=0;i<s.length();i++){
            if(p==s[i]){
                len++;
                continue;
            }else{
                v.pb(len);
                p=s[i];
                len=1;
            }
        }
        v.pb(len);
        map<ll,ll>m;
        forr(i,0,v.size()){
            m[i]=v[i];
            ss.insert(mp(v[i],i));
        }
        ll ind=0;
        ll ans=0;
        while(ind<int(v.size())){
            ll val = m[ind];
            if(val>1){
                ans+=1;
                ss.erase(ss.find(mp(val,ind)));
                ind++;
            }else{
                pair<ll,ll> new_obj = *ss.rbegin();
                ll new_val = new_obj.fi;
                // cout<<new_val<<" ";
                if(new_val>1){
                    ss.erase(ss.find(new_obj));
                    ss.insert(mp(new_val-1,new_obj.se));
                    m[new_obj.se]=new_val-1;
                    ind++;
                    ans++;
                }else{
                    ind+=2;
                    ans++;
                }
            }
        }
        cout<<ans<<"\n";
    }
}


#include<bits/stdc++.h>
// #include <ext/pb_ds/assoc_container.hpp> // Common file
// #include <ext/pb_ds/tree_policy.hpp>
#define pb push_back
#define mp make_pair
#define fi first
#define se second
#define MOD 1000000007
#define MOD9 1000000009
#define pi 3.1415926535
#define ms(s, n) memset(s, n, sizeof(s))
#define prec(n) fixed<<setprecision(n)s
#define eps 0.000001
#define all(v) v.begin(), v.end()
#define allr(v) v.rbegin(), v.rend()
#define bolt ios::sync_with_stdio(0)
#define light cin.tie(0);cout.tie(0)
#define forr(i,p,n) for(ll i=p;i<(ll)n;i++)
typedef long long ll;
using namespace std;
// using namespace __gnu_pbds;

// typedef tree<pair<ll,ll>, null_type, less<pair<ll,ll> >, rb_tree_tag,
//              tree_order_statistics_node_update>
//     pb_ds;

ll mult(ll a,ll b, ll p=MOD){return ((a%p)*(b%p))%p;}
ll multbig(ll a,ll b,ll mod){
    if(a==0 or b==0) return 0;
    if(a==1 or b==1) return (a*b)%mod;
    ll cur=multbig(a,b/2,mod);
    cur=(2*cur)%mod;
    if(b%2) cur=(cur+a)%mod;
    return cur;
}
ll add(ll a, ll b, ll p=MOD){return (a%p + b%p)%p;}
ll fpow(ll n, ll k, ll p = MOD) {ll r = 1; for (; k; k >>= 1LL) {if (k & 1LL) r = mult(r,n,p); n = mult(n,n,p);} return r;}
ll inv(ll a, ll p = MOD) {return fpow(a, p - 2, p);}
ll inv_euclid(ll a, ll m = MOD){ll m0 = m;ll y = 0, x = 1;if (m == 1)return 0;while (a > 1){ll q = a / m;ll t = m;m = a % m, a = t;t = y;y = x - q * y;x = t;}if (x < 0)x += m0;return x;}
void google_cp_output(ll ans, ll &cnt){cout<<"Case #"<<cnt<<": ";cout<<ans<<"\n";cnt+=1;}

//#define MAXN 10003
//ll spff[MAXN];

// void spf(){
//     spff[0]=1;
//     spff[1]=1;
//     for(ll i=2;i<MAXN;i++){
//         if(i%2==0){
//             spff[i]=2;
//         }else spff[i]=i;
//     }
//     for(ll i=3;i*i<=MAXN;i++){
//         if(spff[i]==i){
//             for(ll j=i*i;j<=MAXN;j+=i){
//                 // if(spff[j]==j){
//                     spff[j]=i;
//                 // }
//             }
//         }
//     }
// }

void updateBIT(ll BITree[], ll n, ll index, ll val)
{
    // index in BITree[] is 1 more than the index in arr[]
    index = index + 1;

    // Traverse all ancestors and add 'val'
    while (index <= n)
    {
        // Add 'val' to current node of BI Tree
        BITree[index] += val;

        // Update index to that of parent in update View
        index += index & (-index);
    }
}

// Constructs and returns a Binary Indexed Tree for given
// array of size n.
ll *constructBITree(ll arr[], ll n)
{
    // Create and initialize BITree[] as 0
    ll *BITree = new ll[n+1];
    for (int i=1; i<=n; i++)
        BITree[i] = 0;

    // Store the actual values in BITree[] using update()
    for (int i=0; i<n; i++)
        updateBIT(BITree, n, i, arr[i]);

    // Uncomment below lines to see contents of BITree[]
    //for (int i=1; i<=n; i++)
    //      cout << BITree[i] << " ";

    return BITree;
}

// SERVES THE PURPOSE OF getElement()
// Returns sum of arr[0..index]. This function assumes
// that the array is preprocessed and partial sums of
// array elements are stored in BITree[]
ll getSum(ll BITree[], ll index)
{
    ll sum = 0; // Iniialize result

    // index in BITree[] is 1 more than the index in arr[]
    index = index + 1;

    // Traverse ancestors of BITree[index]
    while (index>0)
    {
        // Add current element of BITree to sum
        sum += BITree[index];

        // Move index to parent node in getSum View
        index -= index & (-index);
    }
    return sum;
}

// Updates such that getElement() gets an increased
// value when queried from l to r.
void update(ll BITree[], ll l, ll r, ll n, ll val)
{
    // Increase value at 'l' by 'val'
    updateBIT(BITree, n, l, val);

    // Decrease value at 'r+1' by 'val'
    updateBIT(BITree, n, r+1, -val);
}

// // Driver program to test above function
// int main()
// {
//     // Add 2 to all the element from [2,4]
//     int l = 2, r = 4, val = 2;
//     update(BITree, l, r, n, val);
//
//     // Find the element at Index 4
//     int index = 4;
//     cout << "Element at index " << index << " is " <<
//          getSum(BITree,index) << "\n";
//
//     // Add 2 to all the element from [0,3]
//     l = 0, r = 3, val = 4;
//     update(BITree, l, r, n, val);
//
//     // Find the element at Index 3
//     index = 3;
//     cout << "Element at index " << index << " is " <<
//          getSum(BITree,index) << "\n" ;
//
//     return 0;
// }

int main(){
    // bolt;
    // light;
    ll t;
    cin>>t;
    while(t--){
        ll n;
        cin>>n;
        string s;
        cin>>s;
        deque<pair<ll,ll> >ss;
        vector<ll>v;
        char p = s[0];
        ll len=0;
        for(ll i=0;i<s.length();i++){
            if(p==s[i]){
                len++;
                continue;
            }else{
                v.pb(len);
                p=s[i];
                len=1;
            }
        }
        v.pb(len);
        // for(auto e:v){
        //     cout<<e<<" ";
        // }
        map<ll,ll>m;
        forr(i,0,v.size()){
            m[i]=v[i];
            if(v[i]>1){
                ss.pb(mp(v[i],i));
            }
        }
        ll ind=0;
        ll ans=0;
        while(ind<int(v.size())){
            ll val = m[ind];
            if(val>1){
                ans+=1;
                pair<ll,ll>p = ss.front();
                if(p.se==ind){
                    ss.pop_front();
                }
                ind++;
            }else{
                if(ss.size()>0){
                    pair<ll,ll> new_obj = ss.front();
                    ll new_val = new_obj.fi;
                    m[new_obj.se]=new_val-1;
                    if(new_val-1>1){
                        ss.push_front(mp(new_val-1,new_obj.se));
                    }
                    ind++;
                    ans++;
                }else{
                    ind+=2;
                    ans++;
                }
            }
        }
        cout<<ans<<"\n";
    }
}


#include<bits/stdc++.h>
// #include <ext/pb_ds/assoc_container.hpp> // Common file
// #include <ext/pb_ds/tree_policy.hpp>
#define pb push_back
#define mp make_pair
#define fi first
#define se second
#define MOD 1000000007
#define MOD9 1000000009
#define pi 3.1415926535
#define ms(s, n) memset(s, n, sizeof(s))
#define prec(n) fixed<<setprecision(n)s
#define eps 0.000001
#define all(v) v.begin(), v.end()
#define allr(v) v.rbegin(), v.rend()
#define bolt ios::sync_with_stdio(0)
#define light cin.tie(0);cout.tie(0)
#define forr(i,p,n) for(ll i=p;i<(ll)n;i++)
typedef long long ll;
using namespace std;
// using namespace __gnu_pbds;

// typedef tree<pair<ll,ll>, null_type, less<pair<ll,ll> >, rb_tree_tag,
//              tree_order_statistics_node_update>
//     pb_ds;

ll mult(ll a,ll b, ll p=MOD){return ((a%p)*(b%p))%p;}
ll multbig(ll a,ll b,ll mod){
    if(a==0 or b==0) return 0;
    if(a==1 or b==1) return (a*b)%mod;
    ll cur=multbig(a,b/2,mod);
    cur=(2*cur)%mod;
    if(b%2) cur=(cur+a)%mod;
    return cur;
}
ll add(ll a, ll b, ll p=MOD){return (a%p + b%p)%p;}
ll fpow(ll n, ll k, ll p = MOD) {ll r = 1; for (; k; k >>= 1LL) {if (k & 1LL) r = mult(r,n,p); n = mult(n,n,p);} return r;}
ll inv(ll a, ll p = MOD) {return fpow(a, p - 2, p);}
ll inv_euclid(ll a, ll m = MOD){ll m0 = m;ll y = 0, x = 1;if (m == 1)return 0;while (a > 1){ll q = a / m;ll t = m;m = a % m, a = t;t = y;y = x - q * y;x = t;}if (x < 0)x += m0;return x;}
void google_cp_output(ll ans, ll &cnt){cout<<"Case #"<<cnt<<": ";cout<<ans<<"\n";cnt+=1;}

//#define MAXN 10003
//ll spff[MAXN];

// void spf(){
//     spff[0]=1;
//     spff[1]=1;
//     for(ll i=2;i<MAXN;i++){
//         if(i%2==0){
//             spff[i]=2;
//         }else spff[i]=i;
//     }
//     for(ll i=3;i*i<=MAXN;i++){
//         if(spff[i]==i){
//             for(ll j=i*i;j<=MAXN;j+=i){
//                 // if(spff[j]==j){
//                     spff[j]=i;
//                 // }
//             }
//         }
//     }
// }

void updateBIT(ll BITree[], ll n, ll index, ll val)
{
    // index in BITree[] is 1 more than the index in arr[]
    index = index + 1;

    // Traverse all ancestors and add 'val'
    while (index <= n)
    {
        // Add 'val' to current node of BI Tree
        BITree[index] += val;

        // Update index to that of parent in update View
        index += index & (-index);
    }
}

// Constructs and returns a Binary Indexed Tree for given
// array of size n.
ll *constructBITree(ll arr[], ll n)
{
    // Create and initialize BITree[] as 0
    ll *BITree = new ll[n+1];
    for (int i=1; i<=n; i++)
        BITree[i] = 0;

    // Store the actual values in BITree[] using update()
    for (int i=0; i<n; i++)
        updateBIT(BITree, n, i, arr[i]);

    // Uncomment below lines to see contents of BITree[]
    //for (int i=1; i<=n; i++)
    //      cout << BITree[i] << " ";

    return BITree;
}

// SERVES THE PURPOSE OF getElement()
// Returns sum of arr[0..index]. This function assumes
// that the array is preprocessed and partial sums of
// array elements are stored in BITree[]
ll getSum(ll BITree[], ll index)
{
    ll sum = 0; // Iniialize result

    // index in BITree[] is 1 more than the index in arr[]
    index = index + 1;

    // Traverse ancestors of BITree[index]
    while (index>0)
    {
        // Add current element of BITree to sum
        sum += BITree[index];

        // Move index to parent node in getSum View
        index -= index & (-index);
    }
    return sum;
}

// Updates such that getElement() gets an increased
// value when queried from l to r.
void update(ll BITree[], ll l, ll r, ll n, ll val)
{
    // Increase value at 'l' by 'val'
    updateBIT(BITree, n, l, val);

    // Decrease value at 'r+1' by 'val'
    updateBIT(BITree, n, r+1, -val);
}

// // Driver program to test above function
// int main()
// {
//     // Add 2 to all the element from [2,4]
//     int l = 2, r = 4, val = 2;
//     update(BITree, l, r, n, val);
//
//     // Find the element at Index 4
//     int index = 4;
//     cout << "Element at index " << index << " is " <<
//          getSum(BITree,index) << "\n";
//
//     // Add 2 to all the element from [0,3]
//     l = 0, r = 3, val = 4;
//     update(BITree, l, r, n, val);
//
//     // Find the element at Index 3
//     index = 3;
//     cout << "Element at index " << index << " is " <<
//          getSum(BITree,index) << "\n" ;
//
//     return 0;
// }

int main(){
    bolt;
    light;
    ll t;
    cin>>t;
    while(t--){
        ll n;
        cin>>n;
        string s;
        cin>>s;
        multiset<pair<ll,ll> >ss;
        vector<ll>v;
        char p = s[0];
        ll len=0;
        for(ll i=0;i<s.length();i++){
            if(p==s[i]){
                len++;
                continue;
            }else{
                v.pb(len);
                p=s[i];
                len=1;
            }
        }
        v.pb(len);
        map<ll,ll>m;
        forr(i,0,v.size()){
            m[i]=v[i];
            ss.insert(mp(v[i],i));
        }
        ll ind=0;
        ll ans=0;
        while(ind<int(v.size())){
            ll val = m[ind];
            if(val>1){
                ans+=1;
                ss.erase(ss.find(mp(val,ind)));
                ind++;
            }else{
                pair<ll,ll> new_obj = *ss.rbegin();
                ll new_val = new_obj.fi;
                if(new_val>1){
                    ss.erase(ss.find(new_obj));
                    ss.insert(mp(new_val-1,new_obj.se));
                    m[new_obj.se]=new_val-1;
                    ind++;
                    ans++;
                }else{
                    ind+=2;
                    ans++;
                }
            }
        }
        cout<<ans<<"\n";
    }
}