結果
| 問題 | No.1094 木登り / Climbing tree |
| ユーザー |
|
| 提出日時 | 2020-10-19 00:55:33 |
| 言語 | Lua (LuaJit 2.1.1734355927) |
| 結果 |
AC
|
| 実行時間 | 1,396 ms / 2,000 ms |
| コード長 | 2,400 bytes |
| コンパイル時間 | 98 ms |
| コンパイル使用メモリ | 5,248 KB |
| 実行使用メモリ | 80,452 KB |
| 最終ジャッジ日時 | 2024-11-08 07:11:40 |
| 合計ジャッジ時間 | 28,670 ms |
|
ジャッジサーバーID (参考情報) |
judge5 / judge4 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 1 |
| other | AC * 26 |
ソースコード
local Deque={}
Deque.lpush=function(self,value)
local first=self.first-1
self.first=first
self[first]=value
end
Deque.rpush=function(self,value)
local last=self.last+1
self.last=last
self[last]=value
end
Deque.lpop=function(self)
local first=self.first
local value=self[first]
self[first]=nil
self.first=first+1
return value
end
Deque.rpop=function(self)
local last=self.last
local value=self[last]
self[last]=nil
self.last=last-1
return value
end
Deque.size=function(self)
return self.last-self.first+1
end
Deque.empty=function(self)
return self.first>self.last
end
Deque.new=function()
return setmetatable({first=0,last=-1},{__index=Deque})
end
----------
local INF=10^20
local function bfs(graph,start)
local dist={}
local rank={0}
local par={}
for i=1,#graph do
dist[i]=INF
par[i]=start
end
local que=Deque:new()
dist[start]=0
que:rpush(start)
while not que:empty() do
local from=que:lpop()
for to,cost in pairs(graph[from]) do
if dist[to]>dist[from]+cost then
dist[to]=dist[from]+cost
rank[to]=rank[from]+1
par[to]=from
que:rpush(to)
end
end
end
return dist,rank,par
end
----------
local n=io.read("*n")
local tree={}
for i=1,n do
tree[i]={}
end
for i=1,n-1 do
local a,b,c=io.read("*n","*n","*n")
tree[a][b]=c
tree[b][a]=c
end
local root=1
local dist
local rank
local par={}
dist,rank,par[1]=bfs(tree,root)
local bit=require("bit")
local k=1
while bit.lshift(1,k)<n do
k=k+1
end
for i=2,k do
par[i]={}
for j=1,n do
par[i][j]=root
end
end
for i=1,k-1 do
for j=1,n do
if par[i][j]~=root then
par[i+1][j]=par[i][par[i][j]]
end
end
end
local q=io.read("*n")
for i=1,q do
local s,t=io.read("*n","*n")
local length=dist[s]+dist[t]
if rank[s]<rank[t] then
s,t=t,s
end
for j=1,k do
if bit.band(bit.rshift((rank[s]-rank[t]),(j-1)),1)>0 then
s=par[j][s]
end
end
if s~=t then
for j=k,1,-1 do
if par[j][s]~=par[j][t] then
s=par[j][s]
t=par[j][t]
end
end
s=par[1][s]
end
io.write(length-2*dist[s].."\n")
end