結果

問題 No.2630 Colorful Vertices and Cheapest Paths
ユーザー rlangevinrlangevin
提出日時 2024-02-16 21:58:38
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 2,203 ms / 2,500 ms
コード長 2,602 bytes
コンパイル時間 171 ms
コンパイル使用メモリ 82,456 KB
実行使用メモリ 160,936 KB
最終ジャッジ日時 2024-09-28 20:16:49
合計ジャッジ時間 25,373 ms
ジャッジサーバーID
(参考情報)
judge2 / judge4
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 22
権限があれば一括ダウンロードができます

ソースコード

diff #

import sys
input = sys.stdin.readline

#https://github.com/shakayami/ACL-for-python/blob/master/dsu.py
class dsu():
    n=1
    parent_or_size=[-1 for i in range(n)]
    def __init__(self,N):
        self.n=N
        self.parent_or_size=[-1 for i in range(N)]
    def merge(self,a,b):
        assert 0<=a<self.n, "0<=a<n,a={0},n={1}".format(a,self.n)
        assert 0<=b<self.n, "0<=b<n,b={0},n={1}".format(b,self.n)
        x=self.leader(a)
        y=self.leader(b)
        if x==y:
            return x
        if (-self.parent_or_size[x]<-self.parent_or_size[y]):
            x,y=y,x
        self.parent_or_size[x]+=self.parent_or_size[y]
        self.parent_or_size[y]=x
        return x
    def same(self,a,b):
        assert 0<=a<self.n, "0<=a<n,a={0},n={1}".format(a,self.n)
        assert 0<=b<self.n, "0<=b<n,b={0},n={1}".format(b,self.n)
        return self.leader(a)==self.leader(b)
    def leader(self,a):
        assert 0<=a<self.n, "0<=a<n,a={0},n={1}".format(a,self.n)
        if (self.parent_or_size[a]<0):
            return a
        self.parent_or_size[a]=self.leader(self.parent_or_size[a])
        return self.parent_or_size[a]
    def size(self,a):
        assert 0<=a<self.n, "0<=a<n,a={0},n={1}".format(a,self.n)
        return -self.parent_or_size[self.leader(a)]
    def groups(self):
        leader_buf=[0 for i in range(self.n)]
        group_size=[0 for i in range(self.n)]
        for i in range(self.n):
            leader_buf[i]=self.leader(i)
            group_size[leader_buf[i]]+=1
        result=[[] for i in range(self.n)]
        for i in range(self.n):
            result[leader_buf[i]].append(i)
        result2=[]
        for i in range(self.n):
            if len(result[i])>0:
                result2.append(result[i])
        return result2

N, M = map(int, input().split())
A, B = [-1] * M, [-1] * M
for i in range(M):
    A[i], B[i] = map(int, input().split())
    A[i], B[i] = A[i] - 1, B[i] - 1
    
C = list(map(int, input().split()))
for i in range(N):
    C[i] -= 1
W = list(map(int, input().split()))
K = 1 << 10
U = [dsu(N) for _ in range(K)]
cost = [0] * K
for s in range(K):
    for i in range(M):
        if ((s >> C[A[i]]) & 1) and ((s >> C[B[i]]) & 1):
            U[s].merge(A[i], B[i])
    for i in range(10):
        if (s >> i) & 1:
            cost[s] += W[i]
          
Q = int(input())
inf = 10 ** 18  
for _ in range(Q):
    ans = inf
    u, v = map(int, input().split())
    u, v = u - 1, v - 1
    for i in range(K):
        if U[i].same(u, v):
            ans = min(ans, cost[i])
         
    print(ans) if ans != inf else print(-1)
0