結果

問題 No.1442 I-wate Shortest Path Problem
ユーザー first_vilfirst_vil
提出日時 2021-02-01 00:45:13
言語 Python3
(3.12.2 + numpy 1.26.4 + scipy 1.12.0)
結果
TLE  
実行時間 -
コード長 1,849 bytes
コンパイル時間 198 ms
コンパイル使用メモリ 12,928 KB
実行使用メモリ 111,264 KB
最終ジャッジ日時 2024-04-19 21:14:24
合計ジャッジ時間 20,218 ms
ジャッジサーバーID
(参考情報)
judge2 / judge5
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 32 ms
17,952 KB
testcase_01 AC 32 ms
11,136 KB
testcase_02 AC 76 ms
13,824 KB
testcase_03 AC 567 ms
22,144 KB
testcase_04 AC 74 ms
13,312 KB
testcase_05 AC 53 ms
12,544 KB
testcase_06 AC 558 ms
22,144 KB
testcase_07 AC 63 ms
12,416 KB
testcase_08 AC 476 ms
21,120 KB
testcase_09 AC 117 ms
16,256 KB
testcase_10 AC 608 ms
23,040 KB
testcase_11 AC 533 ms
22,656 KB
testcase_12 AC 2,984 ms
100,004 KB
testcase_13 AC 1,166 ms
70,144 KB
testcase_14 AC 2,129 ms
90,684 KB
testcase_15 AC 1,882 ms
83,456 KB
testcase_16 AC 2,887 ms
99,712 KB
testcase_17 TLE -
testcase_18 -- -
testcase_19 -- -
testcase_20 -- -
testcase_21 -- -
testcase_22 -- -
testcase_23 -- -
testcase_24 -- -
testcase_25 -- -
testcase_26 -- -
権限があれば一括ダウンロードができます

ソースコード

diff #

def main():
  import sys
  input=sys.stdin.buffer.readline
  sys.setrecursionlimit(10**7)
  
  from heapq import heappush,heappop
  
  n,k=map(int,input().split())
  g=[[]for _ in range(n+k)]
  for _ in range(n-1):
    a,b,c=map(int,input().split())
    a-=1
    b-=1
    g[a].append((b,c))
    g[b].append((a,c))
  
  logn=17
  dep=[0]*n
  dis=[1<<60]*n
  nxt=[[-1]*n for _ in range(logn)]
  def dfs(cur,par,cur_dep,cur_dis):
    dep[cur]=cur_dep
    dis[cur]=cur_dis
    nxt[0][cur]=par
    for to,cost in g[cur]:
      if to!=par:
        dfs(to,cur,cur_dep+1,cur_dis+cost)
  dfs(0,-1,0,0)
  for j in range(logn-1):
    for i in range(n):
      if nxt[j][i]!=-1:
        nxt[j+1][i]=nxt[j][nxt[j][i]]
  def lca(a,b):
    if dep[a]>dep[b]:
      a,b=b,a
    d=dep[b]-dep[a]
    for j in range(logn):
      if d>>j&1:
        b=nxt[j][b]
    if a==b:
      return a
    for j in range(logn-1,-1,-1):
      if nxt[j][a]!=nxt[j][b]:
        a=nxt[j][a]
        b=nxt[j][b]
    return nxt[0][a]
  def dist(a,b):
    return dis[a]+dis[b]-dis[lca(a,b)]*2
  
  p=[0]*k
  for i in range(k):
    m,p[i]=map(int,input().split())
    xs=list(map(int,input().split()))
    for x in xs:
      g[n+i].append((x-1,0))
      g[x-1].append((n+i,p[i]))
  
  dp=[[1<<60]*(n+k)for _ in range(k)]
  dik=[]
  for i in range(k):
    dp[i][n+i]=0
    heappush(dik,(0,n+i))
    while dik:
      d,cur=heappop(dik)
      if dp[i][cur]<d:
        continue
      for to,cost in g[cur]:
        if dp[i][to]>dp[i][cur]+cost:
          dp[i][to]=dp[i][cur]+cost
          dik.append((dp[i][to],to))
  
  output=[]
  q=int(input())
  for _ in range(q):
    u,v=map(int,input().split())
    u-=1
    v-=1
    ans=dist(u,v)
    for i in range(k):
      if ans>dp[i][u]+dp[i][v]+p[i]:
        ans=dp[i][u]+dp[i][v]+p[i]
    output.append(str(ans))
  print('\n'.join(output))
main()
0