我正在练习有关黑客等级的图表问题。以下是问题的链接
https://www.hackerrank.com/challenges/tripartite-matching
我写了一段代码,代码似乎运行在给出的测试用例上。我创建了一些我自己的测试用例并手动计算输出,然后运行我的程序,它的工作原理。但是,对于Hacker Rank上的大多数其他测试用例。我得到一个运行时错误。我不确定它是哪个运行时错误。
我认为我的逻辑正在打破大输入尺寸。但我不确定如何。
以下是我的代码。
'''
Input Sequence
3
2
1 2
2 3
3
1 2
1 3
2 3
2
1 3
2 3
'''
#Stores the data of the graph
class Graph:
def __init__(self,parent_node,child_node):
self.node_map = {}
self.node_map[parent_node] = [child_node]
self.node_map[child_node] = [parent_node]
def getNodeMap(self):
return self.node_map
def deleteKey(self, parent_node):
del self.node_map[parent_node]
def printGraph(self):
print self.node_map
def getChildren(self, parent_node):
return self.node_map[parent_node]
def getAllParents(self):
return self.node_map.keys()
def add(self,parent_node,child_node):
#Adding the Node and Edge Details
# Adding Parent and Child
if (parent_node in self.node_map):
child_list = []
child_list = self.node_map[parent_node]
child_list.append(child_node)
self.node_map[parent_node] = child_list
else:
self.node_map[parent_node] = [child_node]
if (child_node in self.node_map):
parent_list = self.node_map[child_node]
parent_list.append(parent_node)
self.node_map[child_node] = parent_list
else:
self.node_map[child_node] = [parent_node]
def runDFS(parent,seq,graph_num):
#print seq
if(graph_num == len(all_graphs)):
all_sequences.append(seq)
return
else:
if(parent not in all_graphs[graph_num].getAllParents()):
return
children = all_graphs[graph_num].getChildren(parent)
for child in children:
new_set = copy.deepcopy(s)
new_seq = copy.deepcopy(seq)
new_seq.append(child)
runDFS(child,new_seq,graph_num+1)
import sys
import fileinput
import copy
import sys
all_graphs = []
all_sequences = []
list_sequences = []
graphs = raw_input()
#print 'Graphs are', graphs
g = [Graph for i in range(int(graphs))]
for i in range(0,int(graphs)):
g[i] = Graph(-999*i,-999*i)
#print 'Read no. of Edges'
edges = raw_input()
#print edges
for j in range(0,int(edges)):
#print 'Read Edge Info'
edge_info = raw_input()
parent_node = edge_info[0]
child_node = edge_info[2]
g[i].add(parent_node, child_node)
g[i].deleteKey(-999*i)
all_graphs.append(g[i])
#for i in range(0,len(all_graphs)):
# print all_graphs[i].getNodeMap()
graph_num = 0
all_sequences = []
sys.setrecursionlimit(20000)
for item in all_graphs[graph_num].getAllParents():
s = set()
s.add(item)
seq = list()
seq.append(item)
runDFS(item,seq,graph_num)
#print all_sequences
counter = 0
for item in all_sequences:
#print item
end_node = item[len(item)-1]
start_node = item[0]
if(end_node == start_node):
counter = counter + 1
print counter
非常感谢一些帮助。我的逻辑中是否存在错误,或者我的假设是正确的?
如果代码不适用于更大的输入尺寸而不是优化它的最佳方式?
我没有运行DFS,而是使用了以下方法。但同样的事情也发生在这里。我认为我的IO存在一些问题。我无法弄清楚...... :(
for itemA in all_graphs[0].getAllParents():
for itemB in all_graphs[0].getChildren(itemA):
for itemC in all_graphs[1].getChildren(itemB):
if(itemA in all_graphs[2].getChildren(itemC)):
counter = counter + 1
print counter