Problem:


こぶたぬきつねこ

  A子さんの家に親戚のB男君がやってきました。彼は3歳で歌が大好きです。彼は幼稚園でならった「こぶたぬきつねこ」(山本直純作詞・作曲)という歌を一生懸命に歌っています。この歌では、4つのことば「こぶた」  「たぬき」 「きつね」「ねこ」が順にしりとりになっていて、さらに最後の音と最初の音が同じになっています。B男君は、A子さんに、同じようなしりとりが、B男君が言った単語から作れるか教えて欲しいと言われました。

    そこで、A子さんを助けるために、与えられた単語から、その単語をすべて使って、順にしりとりをつくり、その上で、 第1 の単語の最初の文字と最終の単語の最後の文字が同じであるようにできるか否かを判定するプログラムを作成しましょう。

  n 個の単語を入力とし、それらの単語の組からしりとりを作成できるか否かを判定し、可能な場合はOK と、不可能な場合は NG と出力するプログラムを作成してください。

Input

複数のデータセットの並びが入力として与えられます。入力の終わりはゼロひとつの行で示されます。
各データセットは以下の形式で与えられます。

n
word1
word2
:
wordn

 1 行目に単語の個数 n (2 ≤ n ≤ 10000) が与えられます。続く n 行に n 個の単語 wordi (32 文字以下の半角英小文字だけからなる文字列) が与えられます。

データセットの数は 50 を超えません。

Output

入力データセットごとに、判定結果を１行に出力します。

Sample Input

5
apple
yellow
georgia
king
email
7
apple
yellow
georgia
king
email
wink
lucky
0

Output for the Sample Input

NG
OK



Sample input:
5
apple
yellow
georgia
king
email
7
apple
yellow
georgia
king
email
wink
lucky
0


Sample output:
NG
OK

Submission status: Wrong Answer

Solution code:
while True:
  n = int(raw_input())
  if n==0:
    break
  dic = {}
  for _ in xrange(n):
    word = raw_input()
    if word[0] in dic:
      del dic[word[0]]
    else:
      dic[word[0]] = True
    if word[len(word)-1] in dic:
      del dic[word[len(word)-1]]
    else:
      dic[word[len(word)-1]] = True
  if len(dic) == 0:
    print "OK"
  else:
    print "NG"
  dic = {}

Submission status: Wrong Answer

Solution code:
def linked(node, path):
  q = []
  q.append(node.keys()[0])
  node[node.keys()[0]] = True
  while True:
    if len(q) == 0:
      break
    s = q.pop()
    if s in path:
      lst = path[s]
      for k in path[s].keys():
        if node[k] == False:
          node[k] = True
          q.append(k)
  for v in node.values():
    if v == False:
      return False
  return True

while True:
  n = int(raw_input())
  if n==0:
    break
  dic = {}
  node = {}
  path = {}
  for _ in xrange(n):
    word = raw_input()
    node[word[0]] = False
    node[word[len(word)-1]] = False
    if word[0] not in path:
      path[word[0]] = {}
    path[word[0]][word[len(word)-1]] = True

    if word[0] in dic:
      del dic[word[0]]
    else:
      dic[word[0]] = True
    if word[len(word)-1] in dic:
      del dic[word[len(word)-1]]
    else:
      dic[word[len(word)-1]] = True
  if len(dic) == 0:
    if linked(node, path):
      print "OK"
    else:
      print "NG"
  else:
    print "NG"
  dic = {}

Submission status: Wrong Answer

Solution code:
while True:
  n = int(input())
  if n == 0:
    break
  ins = {}
  outs = {}
  for i in range(ord("a"), ord("a") + 26):
    c = chr(i)
    ins[c] = 0
    outs[c] = 0

  for _ in range(n):
    s = input()
    ins[s[-1]] += 1
    outs[s[0]] += 1
  
  for i in range(ord("a"), ord("a") + 26):
    c = chr(i)
    if ins[c] != outs[c]:
      print("NG")
      break
  else:
    print("OK")

Submission status: Wrong Answer

Solution code:
from collections import defaultdict
while True:
    try:
        n=input()
    except SyntaxError:
        break
    if n==0:break
    dic=defaultdict(int)
    for i in range(n):
        w=raw_input()
        dic[w[0]]+=1
        dic[w[-1]]+=1
    if len(set(dic.values()))==1:
        print "OK"
    else:
        print "NG"

Submission status: Wrong Answer

Solution code:
while True:
    try:
        n=input()
    except SyntaxError:
        break
    if n==0:break
    inWd=[0]*26
    outWd=[0]*26
    for i in range(n):
        s=raw_input()
        inWd[ord(s[0])-ord("a")]+=1
        outWd[ord(s[-1])-ord("a")]+=1
    for i in range(26):
        if inWd[i]!=outWd[i]:
            print "NG"
            break
    else:
        print "OK"

Submission status: Wrong Answer

Solution code:
def dfs(u):
    visited[u]=True
    for v in range(26):
        if (not visited[v]) and G[u][v]:
            dfs(v)

def getNComponent():
    nc=0
    for i in range(26):
        if head[i]==0 and tail[i]==0:
            continue
        if not visited[i]:
            nc+=1
            dfs(i)
    return nc

while True:
    try:
        n=input()
        if n==0:break
    except SyntaxError:
	break
    head=[0]*26
    tail=[0]*26
    visited=[False]*26
    G=[[0]*26 for i in range(26)]
    for i in range(n):
        s=raw_input()
        head[ord(s[0])-ord("a")]+=1
        tail[ord(s[-1])-ord("a")]+=1
        G[ord(s[0])-ord("a")][ord(s[-1])-ord("a")]=1
        G[ord(s[-1])-ord("a")][ord(s[0])-ord("a")]=1
    print "OK" if head==tail and getNComponent()==1 else "NG"

Submission status: Wrong Answer

Solution code:
def dfs(u):
    visited[u]=True
    f=False
    for v in range(26):
        if G[u][v]:
            f=True
            if not visited[v]:
                dfs(v)
    return f    

def getNComponent():
    nc=0
    for i in range(26):
        if (not visited[i]) and dfs(i):
            nc+=1
    return nc

while True:
    try:
        n=input()
        if n==0:break
    except SyntaxError:
        break
    head=[0]*26
    tail=[0]*26
    visited=[False]*26
    G=[[0]*26 for i in range(26)]
    for i in range(n):
        s=raw_input()
        a,b=ord(s[0])-ord("a"),ord(s[-1])-ord("a")
        head[a]+=1
        tail[b]+=1
        G[a][b]=G[b][a]=True
    print "OK" if head==tail and getNComponent()==1 else "NG"

Submission status: Wrong Answer

Solution code:
def dfs(u):
    visited[u]=True
    f=False
    for v in range(26):
        if G[u][v]:
            f=True
            if not visited[v]:
                dfs(v)
    return f    

def getNComponent():
    nc=0
    for i in range(26):
        if (not visited[i]) and dfs(i):
            nc+=1
    return nc

while True:
    try:
        n=input()
        if n==0:break
    except SyntaxError:
	break
    head=[0]*26
    tail=[0]*26
    visited=[False]*26
    G=[[False]*26 for i in range(26)]
    for i in range(n):
        s=raw_input()
        a,b=ord(s[0])-ord("a"),ord(s[-1])-ord("a")
        head[a]+=1
        tail[b]+=1
        G[a][b]=G[b][a]=True
    print "OK" if head==tail and getNComponent()==1 else "NG"

Submission status: Wrong Answer

Solution code:
def dfs(current_node):
    visited[current_node] = True
    for next_node in range(26):
        if not visited[next_node] and L[current_node][next_node]:
            dfs(next_node)

def getNComponent():
    count = 0
    for i in range(26):
        if inWd[i]==outWd[i]==0:
            continue
        if not visited[i]:
            count += 1
            dfs(i)
    return count

def check():
    for i in range(26):
        if inWd[i]!=outWd[i]:
            return False
    return True

while True:
    try:
        n = input()
    except SyntaxError:
        break
    if n==0:break
    inWd = [0]*26
    outWd = [0]*26
    visited = [False]*26
    L = [[0]*26 for i in range(26)]
    for i in range(n):
        s = raw_input()
        first_char_num = ord(s[0])-ord("a")
        last_char_num = ord(s[-1])-ord("a")
        inWd[first_char_num] += 1
        outWd[last_char_num] += 1
        L[first_char_num][last_char_num] = 1
        L[last_char_num][first_char_num] = 1
    if check() and getNComponent()==1:
        print "OK"
    else:
        print "NG"

Submission status: Wrong Answer

Solution code:
def dfs(current_node):
    visited[current_node] = True
    for next_node in range(26):
        if not visited[next_node] and L[current_node][next_node]:
            dfs(next_node)

def getNComponent():
    count = 0
    for i in range(26):
        if inWd[i]==0 and outWd[i]==0:
            continue
        if not visited[i]:
            count += 1
            dfs(i)
    return count

def check():
    for i in range(26):
        if inWd[i]!=outWd[i]:
            return False
    return True

while True:
    try:
        n = input()
    except SyntaxError:
        break
    if n==0:break
    inWd = [0]*26
    outWd = [0]*26
    visited = [False]*26
    L = [[0]*26 for i in range(26)]
    for i in range(n):
        s = raw_input()
        first_char_num = ord(s[0])-ord("a")
        last_char_num = ord(s[-1])-ord("a")
        inWd[first_char_num] += 1
        outWd[last_char_num] += 1
        L[first_char_num][last_char_num] = 1
        L[last_char_num][first_char_num] = 1
    if check() and getNComponent()==1:
        print "OK"
    else:
        print "NG"

Submission status: Wrong Answer

Solution code:
def dfs(current_node):
    for next_node in range(26):
        if L[current_node][next_node]:
            L[current_node][next_node] = 0
            visited[current_node] = True
            dfs(next_node)

def getNComponent():
    count = 0
    for i in range(26):
        if inWd[i]==0 and outWd[i]==0:
            continue
        if not visited[i]:
            count += 1
            dfs(i)
    return count

def check():
    for i in range(26):
        if inWd[i]!=outWd[i]:
            return False
    return True

while True:
    try:
        n = input()
    except SyntaxError:
        break
    if n==0:break
    inWd = [0]*26
    outWd = [0]*26
    visited = [False]*26
    L = [[0]*26 for i in range(26)]
    for i in range(n):
        s = raw_input()
        first_char_num = ord(s[0])-ord("a")
        last_char_num = ord(s[-1])-ord("a")
        inWd[first_char_num] += 1
        outWd[last_char_num] += 1
        L[first_char_num][last_char_num] = 1
        L[last_char_num][first_char_num] = 1
    if check() and getNComponent()==1:
        print "OK"
    else:
        print "NG"

Submission status: Wrong Answer

Solution code:
def check():
    for i in range(26):
        if inWd[i] != outWd[i]:
            return False
    return True

def dfs(current_node):
    visited[current_node] = True
    for next_node in range(26):
        if not visited[next_node] and L[current_node][next_node]:
            dfs(next_node)

def getNComponent():
    nc = 0
    for i in range(26):
        if inWd[i] == 0 and outWd[i] == 0:
            continue
        if not visited[i]:
            nc += 1
            dfs(i)
    return nc

while True:
    try:
        n = input()
    except SyntaxError:
        break
    if n==0:break
    inWd = [0]*26
    outWd = [0]*26
    visited = [False]*26
    L = [[0]*26 for i in range(26)]
    for i in range(n):
        s = raw_input()
        first = ord(s[0])-ord("a")
        last = ord(s[-1])-ord("a")
        inWd[first] += 1
        outWd[last] += 1
        L[first][last] = 1
        L[last][first] = 1
    if check() and getNComponent()==1:
        print "OK"
    else:
        print "NG"

Submission status: Wrong Answer

Solution code:
while 1:
	try:
		n=input()
		if n==0: break
		ini,end={},{}
		for	i in range(n):
			word=raw_input()
			try:ini[word[0]]+=1
			except:ini[word[0]]=1
			try:end[word[-1]]+=1
			except:end[word[-1]]=1
		for	k,v in ini.items():
			if k not in end or end[k]!=v:
				print "NG"
				break
		else:
			print "OK"
	except:
		pass

Submission status: Wrong Answer

Solution code:
while 1:
	try:
		n=input()
		if n==0: break
		ini,end={},{}
		for	i in range(n):
			if word[0]==word[-1]:
				continue
			word=raw_input()
			try:ini[word[0]]+=1
			except:ini[word[0]]=1
			try:end[word[-1]]+=1
			except:end[word[-1]]=1
		for	k,v in ini.items():
			if k not in end or end[k]!=v:
				print "NG"
				break
		else:
			print "OK"
	except:
		pass

Submission status: Wrong Answer

Solution code:
while 1:
	try:
		n=input()
		if n==0: break
		ini,end={},{}
		for	i in range(n):
			word=raw_input()
			if word[0]==word[-1]:
				continue
			try:ini[word[0]]+=1
			except:ini[word[0]]=1
			try:end[word[-1]]+=1
			except:end[word[-1]]=1
		for	k,v in ini.items():
			if k not in end or end[k]!=v:
				print "NG"
			break
		else:
			print "OK"
	except:
		pass

Submission status: Wrong Answer

Solution code:
while 1:
	try:
		n=input()
		if n==0: break
		ini,end={},{}
		for	i in range(n):
			word=raw_input()
			if word[0]==word[-1]:
				continue
			try:ini[word[0]]+=1
			except:ini[word[0]]=1
			try:end[word[-1]]+=1
			except:end[word[-1]]=1
		for	k,v in ini.items():
			if k not in end or end[k]!=v:
				print "NG"
				break
		else:
			print "OK"
	except:
		pass

Submission status: Time Limit Exceeded

Solution code:
while True:
        s = []
        e = []
        A = []
        c = input()
        if c==0: break
        for i in range(c):
                STR = raw_input()
                s.append(STR[0])
                e.append(STR[-1])
                z = s+e
                for j in z:     
                        if j not in A: A.append(j)
                        else: continue
        B = list(set(s)& set(e))
        A.sort()
        B.sort()
        print "OK" if B == A else "NG"

Submission status: Accepted

Solution code:
def searchnode(i,u,path):
    r = 1
    u[i] = 1
    for j in range(26):
        if path[i][j] and (not u[j]):
            r += searchnode(j,u,path)
    return r

while(True):
    n = int(input())
    if not n: break
    strs = list(map(lambda x: [x[0],x[-1]], [ input() for i in range(n)]))
    ss,ee = [0]*26,[0]*26
    path = [[0]*26 for _ in range(27)]
    u = [0]*26
    for s,e in strs:
        ss[ord(s)-ord('a')] += 1
        ee[ord(e)-ord('a')] += 1
        path[ord(s)-ord('a')][ord(e)-ord('a')] += 1
    if [1 for s1,e1 in zip(ss,ee) if s1-e1]:
        print("NG")
        continue
    print("OK" if len([1 for s in ss if s]) == searchnode(ord(s)-ord('a'),u,path) else "NG")

Submission status: Accepted

Solution code:
import sys
f = sys.stdin


from collections import defaultdict
from collections import Counter
while True:
    n = int(f.readline())
    if n == 0:
        break
    words = [f.readline().strip() for _ in range(n)]
    words = [(ord(wi[0]) - ord('a'),ord(wi[-1]) - ord('a')) for wi in words]

    pre = Counter(w[0] for w in words)
    post = Counter(w[-1] for w in words)
    if pre != post:
        print('NG')
        continue
        
    path = [[0 for j in range(26)] for i in range(26)]
    for s, e in words:
        path[s][e] = 1
    for k in range(26):
        for i in range(26):
            for j in range(26):
                if path[i][k] and path[k][j]:
                    path[i][j] = 1
    s = words[0][0]
    flg = True
    for k in pre.keys():
        if not path[s][k]:
            flg = False
            break
 
    print('OK' if flg else 'NG')

Submission status: Accepted

Solution code:
def linked(node, path):
  q = []
  q.append(node.keys()[0])
  while True:
    if len(q) == 0:
      break
    s = q.pop()
    if s in path:
      lst = path[s]
      for k in path[s].keys():
        if node[k] == False:
          node[k] = True
          q.append(k)
  for v in node.values():
    if v == False:
      return False
  return True

while True:
  n = int(raw_input())
  if n==0:
    break
  dic = {}
  node = {}
  path = {}
  for _ in xrange(n):
    word = raw_input()
    node[word[0]] = False
    node[word[len(word)-1]] = False
    if word[0] not in path:
      path[word[0]] = {}
    path[word[0]][word[len(word)-1]] = True

    if word[0] in dic:
      del dic[word[0]]
    else:
      dic[word[0]] = True
    if word[len(word)-1] in dic:
      del dic[word[len(word)-1]]
    else:
      dic[word[len(word)-1]] = True
  if len(dic) == 0:
    if linked(node, path):
      print "OK"
    else:
      print "NG"
  else:
    print "NG"
  dic = {}

Submission status: Accepted

Solution code:
from collections import deque

while True:
  n = int(input())
  if n == 0:
    break
  ins = {}
  outs = {}
  node = set()
  base = ord("a")
  edges = [[0] * 26 for _ in range(26)]
  for i in range(26):
    ins[i] = 0
    outs[i] = 0
  
  for _ in range(n):
    s = input()
    fr = ord(s[0]) - base
    to = ord(s[-1]) - base
    ins[to] += 1
    outs[fr] += 1
    edges[fr][to] = 1
    node.add(fr)
    node.add(to)
  
  for i in range(26):
    if ins[i] != outs[i]:
      print("NG")
      break
  else:
    node = sorted(list(node))
    visited = [False] * 26
    visited[node[0]] = True
    que = deque()
    que.append(node[0])
    while que:
      p = que.popleft()
      for i in range(26):
        if edges[p][i] and not visited[i]:
          visited[i] = True
          que.append(i)
    
    for p in node:
      if not visited[p]:
        print("NG")
        break
    else:
      print("OK")

Submission status: Accepted

Solution code:
alphabets = {}
alphabets_num = {}
vartexs = []
fail_check = {}

class Vartex():
    def __init__(self, string):
        global alphabets
        self.ID = string
        self.link = []
        self.arrival = 0
        alphabets[string[0]].append(self)
        alphabets_num[string[0]] += 1
        return

    def register(self, new_vartex):
        self.link.append(new_vartex)
        return

def check_all(vartexs):
    for content in vartexs:
        if not content.arrival:
            return False
    return True

def dfs(start_vartex):
    global vartexs
    start_vartex.arrival = 1
    for link_vartex in start_vartex.link:
        if link_vartex.arrival:
            if check_all(vartexs):
                return True
            else :
                continue
        else:
            if dfs(link_vartex):
                return True
            else:
                continue
    start_vartex.arrival = 0
    return False


while True:
    alphabets = {}
    alphabets_num = {}
    vartexs = []
    fail_check = {}
    for al in range(ord("a"), ord("z")+1):
        alphabets[chr(al)] = []
        alphabets_num[chr(al)] = 0
        fail_check[chr(al)] = 0

    s = raw_input()
    if s == '':
        continue

    n = int(s)

    if not n:
        break

    for x in range(n):
        vartexs.append(Vartex(raw_input()))
    
    for x in range(n):
        vartex = vartexs[x]
        string = vartex.ID
        fail_check[string[-1]] += 1
        for content in alphabets[string[-1]]:
            vartex.register(content)
    
    if alphabets_num != fail_check:
        print "NG"
    else :
        start = vartexs[0]
        if dfs(start):
            print "OK"
        else:
            print "NG"

Submission status: Accepted

Solution code:
alphabets = {}          #This is dict for reference by word's first character
alphabets_num = {}      #saves numbar of that
vartexs = []            #all vertices come out in a single operation
fail_check = {}         #for the check to avoid unnecessary search
 
class Vartex():
    def __init__(self, string):
        global alphabets
        self.ID = string
        self.link = []
        self.hasArrived = False
        return
 
    def register(self, new_vartex):
        self.link.append(new_vartex)
        return

def hasAllArrived(vartexs):
    for content in vartexs:
        if not content.hasArrived:
            return False
    return True
 
def dfs(start_vartex, vartex_list):
    global vartexs

    start_vartex.hasArrived = True

    for link_vartex in start_vartex.link:
        if link_vartex.hasArrived:
            if hasAllArrived(vartex_list):
                return True
            else :
                continue
        else:
            if dfs(link_vartex, vartex_list):
                return True
            else:
                continue
    start_vartex.hasArrived = False
    return False
 
 
while True:
#initalize for global variabale
    alphabets = {}
    alphabets_num = {}
    vartexs = []
    fail_check = {}

    for al in range(ord("a"), ord("z")+1):
        alphabets[chr(al)] = []
        alphabets_num[chr(al)] = 0
        fail_check[chr(al)] = 0
 
#bug appears for some reason without this processing
    s = raw_input()
    if s == '':
        continue
 
    n = int(s)
 
    if not n:
        break
 
    for x in range(n):
        word = raw_input()
        vartex = Vartex(word)
        vartexs.append(vartex)
        alphabets[word[0]].append(vartex)
        alphabets_num[word[0]] += 1
     
    for x in range(n):
        vartex = vartexs[x]
        string = vartex.ID
        fail_check[string[-1]] += 1
        for content in alphabets[string[-1]]:
            vartex.register(content)

#list of the first characters and the last characters must be consistent

    if alphabets_num != fail_check:
        print "NG"
        continue

#depth-first search
    start = vartexs[0]
    if dfs(start, vartexs):
        print "OK"
    else:
        print "NG"

Submission status: Accepted

Solution code:
from collections import deque
ca = ord('a')
while 1:
    N = int(input())
    if N == 0:
        break
    G = [[] for i in range(26)]
    S = [0]*26; T = [0]*26
    for i in range(N):
        word = input()
        s = ord(word[0]) - ca; t = ord(word[-1]) - ca
        S[s] += 1; T[t] += 1
        G[s].append(t)
    ok = 1
    for i in range(26):
        if S[i] != T[i]:
            ok = 0
    if ok:
        que = deque()
        U = [0]*26
        for i in range(26):
            if S[i]:
                que.append(i)
                U[i] = 1
                break
        while que:
            v = que.popleft()
            for w in G[v]:
                if U[w]:
                    continue
                U[w] = 1
                que.append(w)
        for i in range(26):
            if S[i] and not U[i]:
                ok = 0
    print("OK" if ok else "NG")

Submission status: Accepted

Solution code:
from collections import*

def searchnode(i,u,path):  #つなげるものの個数の確認
    r = 1 
    u[i] = 1
#    print(u)
    for j in range(26):
        if path[(i,j)] and (not u[j]):
            r += searchnode(j,u,path)
    return r

def chrtoint(a):
    return ord(a)-ord('a')

while 1:
    n = int(input())
    if n==0:
        break
    inp=[input()for i in range(n)]
    front,back = [0]*26,[0]*26
    path = defaultdict(int)
    u = [0]*26

    for i in inp:
        front[chrtoint(i[0])] += 1
        back[chrtoint(i[-1])] += 1
        path[(chrtoint(i[0]),chrtoint(i[-1]))] += 1

#    print(path)
    if front!=back:
        print("NG")
        continue
    if sum(i!=0 for i in front) == searchnode(chrtoint(i[-1]),u,path):
        print("OK")
    else:
        print("NG")

Submission status: Runtime Error

Solution code:
import sys
R = lambda:map(int,raw_input().split())

def eulerPath(graph):
    odd = [x for x in graph.keys() if len(graph[x])&1]

    if len(odd) > 2: return -1

    stack = [graph.keys()[0]]
    path  = []

    while stack:
        #print stack
        v = stack[-1]
        if graph[v]:
            u = graph[v].pop(0)
            stack.append(u)
            graph[u].remove(v)
            #print graph, stack
        else:
            path.append(stack.pop())

    return path

graph = {}
while 1:
    n = int(raw_input())
    if not n: break
    graph = {}
    for i in xrange(n):
        a = raw_input()
        if not a[0] in graph.keys():
            graph[a[0]] = [a[-1]]
        else:
            graph[a[0]].append(a[-1])
        if not a[-1] in graph.keys():
            graph[a[-1]] = [a[0]]
        else:
            graph[a[-1]].append(a[0])

    path = eulerPath(graph)
    if path is -1: print 'NG'
    else: print 'OK'

Submission status: Runtime Error

Solution code:
from collections import defaultdict
while True:
    n=input()
    if n==0:break
    dic=defaultdict(int)
    for i in range(n):
        w=raw_input()
        dic[w[0]]+=1
        dic[w[-1]]+=1
    if len(set(dic.values()))==1:
        print "OK"
    else:
        print "NG"

Submission status: Runtime Error

Solution code:
from collections import defaultdict
while True:
    try:
        n=input()
    except SyntaxError:
        pass
    if n==0:break
    dic=defaultdict(int)
    for i in range(n):
        w=raw_input()
        dic[w[0]]+=1
        dic[w[-1]]+=1
    if len(set(dic.values()))==1:
        print "OK"
    else:
        print "NG"

Submission status: Runtime Error

Solution code:
alphabets = {}
alphabets_num = {}
vartexs = []
fail_check = {}

class Vartex():
    def __init__(self, string):
        global alphabets
        self.ID = string
        self.link = []
        self.arrival = 0
        alphabets[string[0]].append(self)
        alphabets_num[string[0]] += 1
        return

    def register(self, new_vartex):
        self.link.append(new_vartex)
        return

def check_all(vartexs):
    for content in vartexs:
        if not content.arrival:
            return False
    return True

def dfs(start_vartex):
    global vartexs
    start_vartex.arrival = 1
    for link_vartex in start_vartex.link:
        if link_vartex.arrival:
            if check_all(vartexs):
                return True
            else :
                continue
        else:
            if dfs(link_vartex):
                return True
            else:
                continue
    start_vartex.arrival = 0
    return False


while True:
    alphabets = {}
    alphabets_num = {}
    vartexs = []
    fail_check = {}
    for al in range(ord("a"), ord("z")+1):
        alphabets[chr(al)] = []
        alphabets_num[chr(al)] = 0
        fail_check[chr(al)] = 0

    n = int(raw_input())
    if not n:
        break

    for x in range(n):
        vartexs.append(Vartex(raw_input()))
    
    for x in range(n):
        vartex = vartexs[x]
        string = vartex.ID
        fail_check[string[-1]] += 1
        for content in alphabets[string[-1]]:
            vartex.register(content)
    
    if alphabets_num != fail_check:
        print "NG"
    else :
        start = vartexs[0]
        if dfs(start):
            print "OK"
        else:
            print "NG"

Submission status: Runtime Error

Solution code:
alphabets = {}
alphabets_num = {}
vartexs = []
fail_check = {}

class Vartex():
    def __init__(self, string):
        global alphabets
        self.ID = string
        self.link = []
        self.arrival = 0
        alphabets[string[0]].append(self)
        alphabets_num[string[0]] += 1
        return

    def register(self, new_vartex):
        self.link.append(new_vartex)
        return

def check_all(vartexs):
    for content in vartexs:
        if not content.arrival:
            return False
    return True

def dfs(start_vartex):
    global vartexs
    start_vartex.arrival = 1
    for link_vartex in start_vartex.link:
        if link_vartex.arrival:
            if check_all(vartexs):
                return True
            else :
                continue
        else:
            if dfs(link_vartex):
                return True
            else:
                continue
    start_vartex.arrival = 0
    return False


while True:
    alphabets = {}
    alphabets_num = {}
    vartexs = []
    fail_check = {}
    for al in range(ord("a"), ord("z")+1):
        alphabets[chr(al)] = []
        alphabets_num[chr(al)] = 0
        fail_check[chr(al)] = 0

    n = int(raw_input())
    if n == 0:
        break

    for x in range(n):
        vartexs.append(Vartex(raw_input()))
    
    for x in range(n):
        vartex = vartexs[x]
        string = vartex.ID
        fail_check[string[-1]] += 1
        for content in alphabets[string[-1]]:
            vartex.register(content)
    
    if alphabets_num != fail_check:
        print "NG"
    else :
        start = vartexs[0]
        if dfs(start):
            print "OK"
        else:
            print "NG"

Submission status: Runtime Error

Solution code:
while True:
    n=input()
    if n==0:break
    inWd=[0]*26
    outWd=[0]*26
    for i in range(n):
        s=raw_input()
        inWd[ord(s[0])-ord("a")]+=1
        outWd[ord(s[-1])-ord("a")]+=1
    for i in range(26):
        if inWd[i]!=outWd[i]:
            print "NG"
            break
    else:
        print "OK"

Submission status: Runtime Error

Solution code:
def dfs(u):
    visited[u]=True
    for v in range(26):
        if (not visited[v]) and G[u][v]:
            dfs(v)

def getNComponent():
    nc=0
    for i in range(26):
        if head[i]==0 and tail[i]==0:
            continue
        if not visited[i]:
            nc+=1
            dfs(i)
    return nc

while True:
    n=input()
    if n==0:break
    head=[0]*26
    tail=[0]*26
    visited=[False]*26
    G=[[0]*26 for i in range(26)]
    for i in range(n):
        s=raw_input()
        head[ord(s[0])-ord("a")]+=1
        tail[ord(s[-1])-ord("a")]+=1
        G[ord(s[0])-ord("a")][ord(s[-1])-ord("a")]=1
        G[ord(s[-1])-ord("a")][ord(s[0])-ord("a")]=1
    print "OK" if head==tail and getNComponent()==1 else "NG"

Submission status: Runtime Error

Solution code:
def dfs(u):
    visited[u]=True
    f=False
    for v in range(26):
        if G[u][v]:
            f=True
            if not visited[v]:
                dfs(v)
    return f    

def getNComponent():
    nc=0
    for i in range(26):
        if (not visited[i]) and dfs(i):
            nc+=1
    return nc

while True:
    n=input()
    if n==0:break
    head=[0]*26
    tail=[0]*26
    visited=[False]*26
    G=[[False]*26 for i in range(26)]
    for i in range(n):
        s=raw_input()
        a,b=ord(s[0])-ord("a"),ord(s[-1])-ord("a")
        head[a]+=1
        tail[b]+=1
        G[a][b]=G[b][a]=True
    print "OK" if head==tail and getNComponent()==1 else "NG"

Submission status: Runtime Error

Solution code:
def dfs(current_node):
    for next_node in range(26):
        if L[current_node][next_node]:
            L[current_node][next_node] = 0
            visited[current_node] = True
            dfs(next_node)

def getNComponent():
    count = 0
    for i in range(26):
        if inWd[i]==0 and outWd[i]==0:
            continue
        if not visited[i]:
            count += 1
            dfs(i)
    return count

def check():
    for i in range(26):
        if inWd[i]!=outWd[i]:
            return False
    return True

while True:
    """
    try:
        n = input()
    except SyntaxError:
        break
    """
    n = input()
    if n==0:break
    inWd = [0]*26
    outWd = [0]*26
    visited = [False]*26
    L = [[0]*26 for i in range(26)]
    for i in range(n):
        s = raw_input()
        first_char_num = ord(s[0])-ord("a")
        last_char_num = ord(s[-1])-ord("a")
        inWd[first_char_num] += 1
        outWd[last_char_num] += 1
        L[first_char_num][last_char_num] = 1
        L[last_char_num][first_char_num] = 1
    if check() and getNComponent()==1:
        print "OK"
    else:
        print "NG"

Submission status: Runtime Error

Solution code:
def check():
    for i in range(26):
        if inWd[i] != outWd[i]:
            return False
    return True

def dfs(current_node):
    visited[current_node] = True
    for next_node in range(26):
        if not visited[next_node] and L[current_node][next_node]:
            dfs(next_node)

def getNComponent():
    nc = 0
    for i in range(26):
        if inWd[i] == 0 and outWd[i] == 0:
            continue
        if not visited[i]:
            nc += 1
            dfs(i)
    return nc

while True:
    try:
        n = input()
    except SyntaxError:
        break
    n = input()
    if n==0:break
    inWd = [0]*26
    outWd = [0]*26
    visited = [False]*26
    L = [[0]*26 for i in range(26)]
    for i in range(n):
        s = raw_input()
        first = ord(s[0])-ord("a")
        last = ord(s[-1])-ord("a")
        inWd[first] += 1
        outWd[last] += 1
        L[first][last] = 1
        L[last][first] = 1
    if check() and getNComponent()==1:
        print "OK"
    else:
        print "NG"