We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
#!/bin/python3importmathimportosimportrandomimportreimportsysimportheapqaspqfromcollectionsimportdefaultdictfromcollectionsimportdeque## Complete the 'shop' function below.## The function is expected to return an INTEGER.# The function accepts following parameters:# 1. INTEGER n# 2. INTEGER k# 3. STRING_ARRAY centers# 4. 2D_INTEGER_ARRAY roads#defgetFishset(k,centers,bitset):forcenterNinrange(0,len(centers)):centers[centerN]=centers[centerN].rstrip().split()limit=int(centers[centerN][0])foreach_finrange(1,limit+1):bitset[centerN+1]|=1<<(int(centers[centerN][each_f])-1)returnbitsetdefgetPath(n,k,centers,roads,bitset,graph):hQ=[]power2=1<<kdist=[[999999forjinrange(power2)]for_inrange(n+1)]visited=[[0forjinrange(power2)]for_inrange(n+1)]bitset=getFishset(k,centers,bitset)pq.heappush(hQ,(0,1,bitset[1]))dist[1][bitset[1]]=0whilehQ:distance,centerN,eachSet=pq.heappop(hQ)ifvisited[centerN][eachSet]==1:continuevisited[centerN][eachSet]=1forneighboringraph[centerN]:bitadd=eachSet|bitset[neighbor[0]]f_dist=distance+neighbor[1]iff_dist<dist[neighbor[0]][bitadd]:dist[neighbor[0]][bitadd]=f_distpq.heappush(hQ,(f_dist,neighbor[0],bitadd))totalCost=999999range_l=len(dist[n])foriinrange(range_l-1,0,-1):ifdist[n][i]==999999:continueifi==(power2-1)anddist[n][i]<totalCost:totalCost=dist[n][i]continueforjinrange(1,i):if(i|j)==(power2-1)andmax(dist[n][i],dist[n][j])<totalCost:totalCost=max(dist[n][i],dist[n][j])returntotalCostdefshop(n,k,centers,roads):bitset=[0for_inrange(n+1)]graph=defaultdict(list)foreachinroads:graph[each[0]].append((each[1],each[2]))graph[each[1]].append((each[0],each[2]))totalCost=getPath(n,k,centers,roads,bitset,graph)returntotalCostif__name__=='__main__':fptr=open(os.environ['OUTPUT_PATH'],'w')first_multiple_input=input().rstrip().split()n=int(first_multiple_input[0])m=int(first_multiple_input[1])k=int(first_multiple_input[2])centers=[]for_inrange(n):centers_item=input()centers.append(centers_item)roads=[]for_inrange(m):roads.append(list(map(int,input().rstrip().split())))res=shop(n,k,centers,roads)fptr.write(str(res)+'\n')fptr.close()
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Synchronous Shopping
You are viewing a single comment's thread. Return to all comments →
Solution in Python