def memoize(f):
def memf(*x):
if x not in memf.cache:
memf.cache[x] = f(*x)
return memf.cache[x]
memf.cache = {}
return memf
class Graph:
def __init__(self,n):
self.n = n
self.nodesColor = {}
self.g = {}
self.color = [None] * n
self.successor = memoize(self.successor)
def addNodeColor(self,t,c):
self.g[t] = []
self.color[t - 1] = c
if self.nodesColor.has_key(c):
self.nodesColor[c].append(t)
else:
self.nodesColor[c] = [t]
def addEdge(self,a,b,cost):
if self.g.has_key(a):
self.g[a].append((b,cost))
else:self.g[a] = [(b,cost)]
def successor(self,a):
return self.g[a]
def done(self):
for n in self.g.keys():
c = self.color[n - 1]
for i in self.nodesColor[c]:
if i != n:
self.g[n].append((i,0))
def shortestPath2(self,a,b):
if a == b:
return 0
shortest = 99999
for i,j in self.successor(a):
cost = self.shortestPath2(i,b)
if cost == None :continue
dist = j + self.shortestPath2(i,b)
if dist < shortest:
shortest = dist
if dist >= 99999: return None
return shortest
def shortestPath(self,a,b):
q = []
visited = set()
heapq.heappush(q,(0,a))
while q != []:
node = heapq.heappop(q)
if node[1] == b:
return node[0]
#print >>stderr,visited
if node[1] not in visited:
visited.add(node[1])
for i,j in self.successor(node[1]):
heapq.heappush(q,(node[0] + j,i))
return -1
def __str__(self):
s = []
for i,j in vars(self).items():
s.append(str(i)+" : "+str(j))
return "\n".join(s)
def solve(_map):
n = int(stdin.readline())
#print _map
stdout.write("\n")
#print >>stderr,"people:",n
for i in range(n):
i,j = stdin.readline().split()
stdout.write(str(_map.shortestPath(int(i),int(j))) + "\n")
def readMap():
n = int(stdin.readline().strip())
#print >> stderr,n
myG = Graph(n)
for i in xrange(1,n + 1):
myG.addNodeColor(i,stdin.readline().strip())
n = int(stdin.readline().strip())
for i in xrange(1,n + 1):
a,b,cost = stdin.readline().strip().split()
myG.addEdge(int(a),int(b), int(cost))
myG.done()
return myG
#---------------------------------------------
from sys import stdin,stdout,stderr
import heapq
import sets
case = int(stdin.readline())
n = 1
while n <= case:
m = readMap()
print >>stderr,n
stdout.write("Case #%d: " % n)
solve(m)
n += 1
https://code.google.com/codejam/contest/2924486/dashboard#s=p4
2013年google 在线笔试第五题被虐记。。
最新推荐文章于 2019-10-11 09:27:11 发布