Prim's (MST) : Special Subtree

  • + 0 comments
    def prims(n, edges, start):
        d={}
        score=0
        for i,j,k in edges:
            if i not in d:
                d[i]=[]
            if j not in d:
                d[j]=[]
            d[i].append([j,k])
            d[j].append([i,k])
        dp=deque([[start,0]])
        m=set()
        while dp:
            a=dp[0][0]
            if a in m:
                dp.popleft()
                continue
            score+=dp[0][1]
            r=dp.popleft()
            m.add(r[0])
            for i,j in d[a]:
                if i in m:
                    continue
                if len(dp)==0:
                    dp.append([i,j])
                else:
                    x=0
                    y=len(dp)-1
                    while y>=x:
                        if j>dp[x][1]:
                            x+=1
                        else:
                            dp.insert(x,[i,j])
                            break
                        if j<dp[y][1]:
                            y-=1
                        else:
                            dp.insert(y+1,[i,j])
                            break    
        return score