結果
問題 | No.1002 Twotone |
ユーザー |
![]() |
提出日時 | 2025-01-24 12:37:08 |
言語 | PyPy3 (7.3.15) |
結果 |
TLE
|
実行時間 | - |
コード長 | 3,687 bytes |
コンパイル時間 | 1,145 ms |
コンパイル使用メモリ | 81,664 KB |
実行使用メモリ | 366,416 KB |
最終ジャッジ日時 | 2025-01-24 12:39:14 |
合計ジャッジ時間 | 122,210 ms |
ジャッジサーバーID (参考情報) |
judge5 / judge4 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 2 |
other | AC * 15 TLE * 18 |
ソースコード
n,K=map(int,input().split())e=[[] for i in range(n)]for _ in range(n-1):a,b,c=map(int,input().split())a-=1b-=1c-=1e[a]+=[(b,c)]e[b]+=[(a,c)]cdc=[]cdp=[-1]*nv=[0]*nu=[0]*ncdq=[0]for start in cdq:q=[start]while len(q)>0:s=q[-1]if v[s]==0:v[s]=1q+=[t for t,_ in e[s] if v[t]==0 and cdp[t]==-1]else:u[s]=1+sum([u[t] for t,_ in e[s] if v[t]==0 and cdp[t]==-1])v[s]=0q.pop()q=[start]while len(q)>0:s=q[-1]if v[s]==0:if all((u[t] if v[t]==0 else u[start]-u[s])<=u[start]//2 or cdp[t]!=-1 for t,_ in e[s]):o=sv[s]=1q+=[t for t,_ in e[s] if v[t]==0 and cdp[t]==-1]else:v[s]=0q.pop()cdp[o]=len(cdc)cdc+=[o]cdq+=[t for t,_ in e[o] if cdp[t]==-1]ans=0v=[0]*nst1=[{} for i in range(n)]st2=[{} for i in range(n)]st3=[0]*Kst4={}st5=[0]*nst6=[0]*Kuc=[0]*Kfor C in cdc[::-1]:st4={}u=set()for root,c in e[C]:if cdp[root]>cdp[C]:st1[root]={}st2[root]={}q=[(root,c)]while len(q)>0:s,sc=q[-1]if v[s]==0:v[s]=1uc[sc]+=1if uc[sc]==1:u.add(sc)if len(u)==1:c1=sorted(u)[0]if c1 not in st1[root]:st1[root][c1]=0st1[root][c1]+=1st3[c1]+=1st5[C]+=1if len(u)==2:c1,c2=sorted(u)c1c2=c1*K+c2if c1c2 not in st2[root]:st2[root][c1c2]=0st2[root][c1c2]+=1if c1c2 not in st4:st4[c1c2]=0st4[c1c2]+=1st6[c1]+=1st6[c2]+=1for t,tc in e[s]:if v[t]==0 and cdp[t]>cdp[C]:q+=[(t,tc)]else:v[s]=0uc[sc]-=1if uc[sc]==0:u.remove(sc)q.pop()ans+=sum(st4[c1c2] for c1c2 in st4)*2u=set()for root,c in e[C]:if cdp[root]>cdp[C]:for c1 in st1[root]:x=st1[root][c1]st3[c1]-=xst5[C]-=xfor c1c2 in st2[root]:x=st2[root][c1c2]st4[c1c2]-=xst6[c1c2//K]-=xst6[c1c2%K]-=xq=[(root,c)]while len(q)>0:s,sc=q[-1]if v[s]==0:v[s]=1uc[sc]+=1if uc[sc]==1:u.add(sc)if len(u)==1:c1=sorted(u)[0]ans+=st5[C]-st3[c1]ans+=st6[c1]*2if len(u)==2:c1,c2=sorted(u)c1c2=c1*K+c2ans+=st4[c1c2]for t,tc in e[s]:if v[t]==0 and cdp[t]>cdp[C]:q+=[(t,tc)]else:v[s]=0uc[sc]-=1if uc[sc]==0:u.remove(sc)q.pop()for c1 in st1[root]:x=st1[root][c1]st3[c1]+=xst5[C]+=xfor c1c2 in st2[root]:x=st2[root][c1c2]st4[c1c2]+=xst6[c1c2//K]+=xst6[c1c2%K]+=xu=set()for root,c in e[C]:if cdp[root]>cdp[C]:q=[(root,c)]while len(q)>0:s,sc=q[-1]if v[s]==0:v[s]=1uc[sc]+=1if uc[sc]==1:u.add(sc)if len(u)==1:c1=sorted(u)[0]st3[c1]-=1st5[C]-=1if len(u)==2:c1,c2=sorted(u)c1c2=c1*K+c2st6[c1]-=1st6[c2]-=1for t,tc in e[s]:if v[t]==0 and cdp[t]>cdp[C]:q+=[(t,tc)]else:v[s]=0uc[sc]-=1if uc[sc]==0:u.remove(sc)q.pop()print(ans//2)