Problem:
Problem A: Membership Management Peter is a senior manager of Agile Change Management (ACM) Inc., where each employee is a member of one or more task groups. Since ACM is agile, task groups are often reorganized and their members frequently change, so membership management is his constant headache. Peter updates the membership information whenever any changes occur: for instance, the following line written by him means that Carol and Alice are the members of the Design Group. design:carol,alice. The name preceding the colon is the group name and the names following it specify its members. A smaller task group may be included in a larger one. So, a group name can appear as a member of another group, for instance, as follows. development:alice,bob,design,eve. Simply unfolding the design above gives the following membership specification, which is equivalent to the original. development:alice,bob,carol,alice,eve. In this case, however, alice occurs twice. After removing one of the duplicates, we have the following more concise specification. development:alice,bob,carol,eve. Your mission in this problem is to write a program that, given group specifications, identifies group members. Note that Peter's specifications can include deeply nested groups. In the following, for instance, the group one contains a single member dave. one:another.
another:yetanother.
yetanother:dave. Input The input is a sequence of datasets, each being in the following format.  n  group 1 : member 1,1 ,..., member 1, m 1 .  .  .  .  group i : member i ,1 ,..., member i , m i .  .  .  .  group n : member n ,1 ,..., member n , m n .  The first line contains n, which represents the number of groups and is a positive integer no more than 100. Each of the following n lines contains the membership information of a group: group i (1 ≤ i ≤ n ) is the name of the i -th task group and is followed by a colon ( : ) and then the list of its m i member s that are delimited by a comma ( , ) and terminated by a period ( . ). Those group names are mutually different. Each m i (1 ≤ i ≤ n ) is between 1 and 10, inclusive. A member is another group name if it is one of group 1 , group 2 ,..., or groupn. Otherwise it is an employee name. There are no circular (or recursive) definitions of group(s). You may assume that m i member names of a group are mutually different. Each group or employee name is a non-empty character string of length between 1 and 15, inclusive, and consists of lowercase letters. The end of the input is indicated by a line containing a zero. Output For each dataset, output the number of employees included in the first group of the dataset, that is group 1 , in a line. No extra characters should occur in the output. Sample Input 2
development:alice,bob,design,eve.
design:carol,alice.
3
one:another.
another:yetanother.
yetanother:dave.
3
friends:alice,bob,bestfriends,carol,fran,badcompany.
bestfriends:eve,alice.
badcompany:dave,carol.
5
a:b,c,d,e.
b:c,d,e,f.
c:d,e,f,g.
d:e,f,g,h.
e:f,g,h,i.
4
aa:bb.
cc:dd,ee.
ff:gg.
bb:cc.
0 Output for the Sample Input 4
1
6
4
2

Solution (Python):
def get_num(u, map, vis):
    if u in vis:
        return 0;
    else:
        vis[u] = True;
    ans = 0;
    if u in map:
        for v in map[u]:
            ans += get_num(v, map, vis);
    else:
            ans += 1;
    return ans;
def main():
    while True:
        n = int(input());
        if n == 0:
            break;
        edge = {}; name = {}; vis = {};
        for i in range(0, n):
            str = input();
            u = name[i] = str.split(':')[0];
            group = str.split(':')[1].split('.')[0].split(',');
            for v in group:
                if u in edge:
                    edge[u][v] = True;
                else:
                    edge[u] = {v:True};
        print(get_num(name[0], edge, vis));
main();

Solution (Python):
def dfs(dg, gs, ms, used, v):
    if used[v]:
        return dg[gs[v]]
    used[v] = 1
    me = ms[v]
    for i in xrange(len(me)):
        if me[i] in dg:
            ret = dfs(dg, gs, ms, used, gs.index(me[i]))
            for e in ret:
                if e not in dg[gs[v]]:
                    dg[gs[v]].append(e)
        else:
            if me[i] not in dg[gs[v]]:
                dg[gs[v]].append(me[i])
    return dg[gs[v]]

while 1:
    n = input()
    if not n:
        break
    gs = []; ms = []
    dg = {}
    for i in xrange(n):
        g, m = raw_input().split(":")
        gs.append(g); ms.append(m[:-1].split(","))
        dg[g] = []

    dfs(dg, gs, ms, [0]*n, 0)
    print len(dg[gs[0]])

Solution (Python):
while True:
    N = int(input())
    if N == 0:
        break
    
    first_group_menbers = set(input()[:-1].split(":")[1].split(","))
    
    d = {}
    for i in range(N-1):
        group, members = input()[:-1].split(":")
        d[group] = set(members.split(","))
        
    for i in range(N):
        for group, members in d.items():
            if group in first_group_menbers:
                first_group_menbers.remove(group)
                for m in members:
                    first_group_menbers.add(m)
    
    print(len(first_group_menbers))

Solution (Python):
while True:
    N = int(input())
    if N == 0:
        break
    
    first_group_menbers = set(input()[:-1].split(":")[1].split(","))
    d = {}
    for i in range(N-1):
        group, members = input()[:-1].split(":")
        d[group] = set(members.split(","))
        
    for i in range(N-1):
        for group, members in d.items():
            if group in first_group_menbers:
                first_group_menbers.remove(group)
                for m in members:
                    first_group_menbers.add(m)
    
    print(len(first_group_menbers))

Solution (Python):
while True:
    N = int(input())
    if N == 0:
        break
    
    first_group_menbers = set(input()[:-1].split(":")[1].split(","))
    d = {}
    for i in range(N-1):
        group, members = input()[:-1].split(":")
        d[group] = set(members.split(","))
        
    for i in range(N-2):
        for group, members in d.items():
            if group in first_group_menbers:
                first_group_menbers.remove(group)
                for m in members:
                    first_group_menbers.add(m)
    
    print(len(first_group_menbers))

Solution (Python):


if __name__ == "__main__":
	while True:
		N = int(raw_input())
		if N == 0:
			break;
		
		name = [""] * N
		member = []
		for i in range(0,N):
			name[i], S = raw_input().strip('.').split(':')
			member.append(S.split(','))
		
		used = [False] * N
		for REP in range(0,N):
			for i in range(0,N):
				if used[i]:
					continue
				if name[i] in member[0]:
					for S in member[i]:
						member[0].append(S)
					member[0] = list(set(member[0]))
					used[i] = True
		
		cnt = 0
		for i in range(0,N):
			if used[i]:
				cnt = cnt + 1
		
		print len(member[0]) - cnt

Solution (Python):


while True:
    n = input()
    if n == 0:
        break
    lst = []
    for i in range(n):
        S = raw_input()
        hoge = S.split(':')
        hoge[1] = hoge[1][:-1].split(',')
        lst.append(hoge)
    mp = {}
    m = {}
    m[lst[0][0]] = 1
    for i in range(200):
        for l in lst:
            if l[0] in m:
                mp[l[0]] = 1
                for S in l[1]:
                    m[S] = 1
    
    print len(m) - len(mp)

Solution (Python):
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools

sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 998244353
dd = [(0,-1),(1,0),(0,1),(-1,0)]
ddn = [(0,-1),(1,-1),(1,0),(1,1),(0,1),(-1,-1),(-1,0),(-1,1)]

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)


def main():
    rr = []

    while True:
        n = I()
        if n == 0:
            break

        a = [S().split(':') for _ in range(n)]
        ts = set([c[0] for c in a])
        ms = {}
        for t,m in a:
            ms[t] = m[:-1].split(',')

        fm = {}
        def f(c):
            if c in fm:
                return fm[c]
            if c in ts:
                s = set()
                for k in ms[c]:
                    s |= f(k)
                fm[c] = s
                return s
            fm[c] = set([c])
            return fm[c]

        r = f(a[0][0])

        rr.append(len(r))

    return '\n'.join(map(str,rr))


print(main())

Solution (Python):
while 1:
	n = input()
	if n == 0: break
	ans = {}
	for i in range(n):
		group,name = raw_input().split(":")
		if i == 0: first = group
		ans[group] = set(name[:-1].split(","))
		while 1:
			for key in ans:
				flag = 0
				if key == first: continue
				for key1 in ans:
					if key in ans[key1]:
						ans[key1] |= ans[key]
						ans[key1].discard(key)
						flag = 1
			if flag == 0: break
	print len(ans[first])

Solution (Python):
while 1:
	n = input()
	if n == 0: break
	ans = {}
	for i in range(n):
		group,name = raw_input().split(":")
		if i == 0: first = group
		ans[group] = set(name[:-1].split(","))
	while 1:
		for key in ans:
			flag = 0
			if key == first: continue
			for key1 in ans:
				if key in ans[key1]:
					ans[key1] |= ans[key]
					ans[key1].discard(key)
					flag = 1
			if flag:
				del ans[key]
				break
		if flag == 0: break
	print len(ans[first])

Solution (Python):
def get_num(u, map, vis):
    if u in vis:
        return 0;
    else:
        vis[u] = True;
    ans = 0;
    if u in map:
        for v in map[u]:
            ans += get_num(v, map, vis);
    else:
            ans += 1;
    return ans;
def main():
    while True:
        n = int(input());
        if n == 0:
            break;
        edge = {}; name = {}; vis = {};
        for i in range(0, n):
            str = input();
            u = name[i] = str.split(':')[0];
            group = str.split(':')[1].split('.')[0].split(',');
            for v in group:
                if u in edge:
                    edge[u][v] = True;
                else:
                    edge[u] = {v:True};
        print(get_num(name[0], edge, vis));
main();

Solution (Python):
import re

N = 1
while True:
    N = int(input())
    if not N:
        break
    tmp, groups, firstgroup = [], {}, []
    for i in range(N):
        tmp = re.split(r"[\,\.\:]", input())
        if not i:
            firstgroup = tmp[1:]

        else:
            groups[tmp[0]] = tmp[1:]

    while True:
        change = False
        tmp = []
        for i in range(len(firstgroup)):
            if firstgroup[i] in groups:
                tmp += groups[firstgroup[i]]
                change = True
            else:
                tmp.append(firstgroup[i])

        firstgroup = ['']
        for i in tmp:
            if i not in firstgroup:
                firstgroup.append(i)

        if not change:
            break
    print(len(firstgroup) - 1)

Solution (Python):
while True:
    n = int(input())
    if n == 0:
        break
    group = dict()
    ls = set()
    for i in range(n):
        g,s = input().split(':')
        group[g] = set(s[:-1].split(','))
        if i == 0:
            ls.add(g)
    ans = set()
    while len(ls) > 0:
        s = ls.pop()
        if s in group.keys():
            ls |= group[s]
        else:
            ans.add(s)
    print(len(ans))

Solution (Python):
while True:
	n = int(input())
	if(n==0): break
	data = {}
	firstname = ''
	for i in range(n):
		d = input()
		name = d.split(':')[0]
		if(i==0): firstname = name
		data[name] = []
		for x in d.split(':')[1].strip('.').split(','):
			data[name].append(x)
	removed = []
	for x in data[firstname]:
		if x in data:
			removed.append(x)
			for y in data[x]:
				data[firstname].append(y)
			data.pop(x)
	edited = set(data[firstname])
	for i in removed:
		edited.remove(i)
	print(len(edited))

Solution (Python):


import sys
import math
import re
from bisect import bisect_right as br
from bisect import bisect_left as bl
sys.setrecursionlimit(1000000)
from heapq import heappush, heappop,heappushpop
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operator import itemgetter
from itertools import permutations
mod = 10**9 + 7
inf = float('inf')
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))

while 1:
    n = I()
    if n == 0:
        quit()
    f = defaultdict(dict)
    t = defaultdict(lambda : False)
    ch = defaultdict(lambda : False)
    stack = []
    for i in range(n):
        x = input()[:-1].split(':')
        y = x[1].split(',')
        x = x[0]
        for j in y:
            f[x][j] = 1
            if i != 0:
                continue
            stack.append(j)
    ans = 0
    while stack:
        x = stack.pop()
        if ch[x]:
            continue
        ch[x] = True
        if len(f[x]) == 0 and not t[x]:
            ans += 1
            t[x] = True
            continue
        for i,j in f[x].items():
            stack.append(i)
    print(ans)

Solution (Python):

from collections import defaultdict,deque
from heapq import heappush, heappop
from bisect import bisect_left, bisect_right
import sys, random, itertools, math
sys.setrecursionlimit(10**5)
input = sys.stdin.readline
sqrt = math.sqrt
def LI(): return list(map(int, input().split()))
def LF(): return list(map(float, input().split()))
def LI_(): return list(map(lambda x: int(x)-1, input().split()))
def II(): return int(input())
def IF(): return float(input())
def LS(): return list(map(list, input().split()))
def S(): return list(input().rstrip())
def IR(n): return [II() for _ in range(n)]
def LIR(n): return [LI() for _ in range(n)]
def FR(n): return [IF() for _ in range(n)]
def LFR(n): return [LI() for _ in range(n)]
def LIR_(n): return [LI_() for _ in range(n)]
def SR(n): return [input().rstrip()[:-1] for _ in range(n)]
def LSR(n): return [LS() for _ in range(n)]
mod = 1000000007
inf = 1e10


def solve():
    n = II()
    if n == 0:
        return False
    group = set()
    go_group = set()
    member = set()
    d = defaultdict(int)
    g = SR(n)
    for gi in g:
        group.add(gi.split(":")[0])
        d[gi.split(":")[0]] = gi.split(":")[1].split(",")
    C = defaultdict(int)
    def s(g):
        for gi in g:
            if gi in group:
                if C[gi]:
                    continue
                C[gi] = 1
                s(d[gi])
            else:
                member.add(gi)
    s(d[g[0].split(":")[0]])
    print(len(member))
    return True


if __name__ == '__main__':
    while solve():
        pass

Solution (Python):

from queue import Queue


def input_split(line):
    group, members = line.rstrip('.').split(':')
    members = members.split(',')
    return group, members


while True:
    n = int(input())
    if n == 0:
        exit()

    data = [input() for _ in range(n)]
    to = {}
    rev = {}
    sz = 0
    for line in data:
        group, members = input_split(line)
        if group not in to:
            to[group] = sz
            rev[sz] = group
            sz += 1
        for m in members:
            if m not in to:
                to[m] = sz
                rev[sz] = m
                sz += 1

    g = [[] for _ in range(sz)]
    indeg = [0] * sz
    for line in data:
        group, members = input_split(line)
        for m in members:
            g[to[m]].append(to[group]) 
            indeg[to[group]] += 1

    dp = [set() for i in range(sz)]
    q = Queue()
    for i in range(sz):
        if indeg[i] == 0:
            dp[i] |= {i}
            q.put(i)
    while not q.empty():
        cur = q.get()
        for nxt in g[cur]:
            dp[nxt] |= dp[cur]
            indeg[nxt] -= 1
            if indeg[nxt] == 0:
                q.put(nxt)
    
    print(len(dp[0]))

Solution (Python):
def check(dic,index):
  ret = []
  for c in dic[index]:
    if c in dic.keys():
      for d in check(dic,c):
        if not(d in ret):
          ret.append(d)
    else:
      if not(c in ret):
        ret.append(c)
  dic[index] = ret
  return ret


while True:
  n = int(input())
  if n == 0:
    break
  dic = {}
  index = ''
  for i in range(n):
   a,b = [char for char in input()[0:-1].split(':')]
   if i == 0:
     index = a
   b = b.split(',')

   dic[a] = b
  
  print(len(check(dic,index)))

Solution (Python):

def addset(args):
    global a
    for m in args:
        if dic[m]==1:
            a.add(m)
        else:
            if m not in used:
                used.add(m)
                addset(dc[m])
 
while True:
    n=int(input())
    if n==0:
        break
    dic={}
    first=[]
    dc={}
    for i in range(n):
        g,m=input().split(':')
        m=m.rstrip('.').split(',')
        dc[g]=m
        if i==0:
            first.append(g)
            first+=m
        dic[g]=2
        for mem in m:
            if mem not in dic:
                dic[mem]=1
    a=set()
    used=set()
    addset(first[1:])
    print(len(a))