結果
| 問題 |
No.2047 Path Factory
|
| コンテスト | |
| ユーザー |
taiga0629kyopro
|
| 提出日時 | 2022-08-19 22:41:45 |
| 言語 | PyPy3 (7.3.15) |
| 結果 |
AC
|
| 実行時間 | 504 ms / 2,000 ms |
| コード長 | 1,889 bytes |
| コンパイル時間 | 458 ms |
| コンパイル使用メモリ | 82,176 KB |
| 実行使用メモリ | 104,192 KB |
| 最終ジャッジ日時 | 2024-10-15 13:32:03 |
| 合計ジャッジ時間 | 8,350 ms |
|
ジャッジサーバーID (参考情報) |
judge5 / judge4 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 3 |
| other | AC * 27 |
ソースコード
def sum2(a):
n=len(a)
ans=sum(a)**2
for x in a:ans-=x**2
ans//=2
return ans
mod=998244353
n=int(input())
root=[[] for i in range(n+3)]
for i in range(n-1):
a,b=map(int,input().split())
root[a].append(b)
root[b].append(a)
oyl=[]
seen=[0]*(n+1)
p=[10**10]*(n+1)
stc=[1]
while stc:
now=stc.pop()
oyl.append(now)
if p[now] in root[now]:root[now].remove(p[now])
for to in root[now]:
if to==p[now]:continue
if seen[to]:continue
seen[to]=1
stc.append(to)
p[to]=now
oyl.reverse()
dp0=[0]*(n+3)
dp1=[0]*(n+3)
dp2=[0]*(n+3)
for v in oyl:
if len(root[v])==0:
dp1[v]=1
continue
dp1[v]=1
for to in root[v]:
dp1[v]*=(dp0[to]+dp2[to])
dp1[v]%=mod
cnt0=0
mul=1
for to in root[v]:
if dp0[to]+dp2[to]==0:cnt0+=1
else:
mul*=dp0[to]+dp2[to]
mul%=mod
for to in root[v]:
mul2=mul
if dp0[to]+dp2[to]>0:
mul2=mul*pow(dp0[to]+dp2[to],mod-2,mod)%mod
if cnt0>=2:continue
if cnt0==1 and dp0[to]+dp2[to]!=0:continue
dp0[v]+=(dp0[to]+dp1[to])*mul2
dp0[v]%=mod
a=[]
if cnt0>=3:continue
elif cnt0==2:
res=mul
for to in root[v]:
if dp0[to]+dp2[to]==0:
res*=dp0[to]+dp1[to]
res%=mod
dp2[v]=res
continue
elif cnt0==1:
ind=10**10
res=0
for to in root[v]:
if dp0[to]+dp2[to]==0:ind=to
else:
res+=(dp0[to]+dp1[to])*pow(dp0[to]+dp2[to],mod-2,mod)
res%=mod
res*=mul
res%=mod
dp2[v]=res*(dp0[ind]+dp1[ind])%mod
continue
for to in root[v]:
a.append((dp0[to]+dp1[to])*pow(dp0[to]+dp2[to],mod-2,mod)%mod)
dp2[v]=(sum2(a)%mod)*mul%mod
print((dp0[1]+dp2[1])%mod)
taiga0629kyopro