結果
問題 | No.1418 Sum of Sum of Subtree Size |
ユーザー |
![]() |
提出日時 | 2021-11-25 15:05:37 |
言語 | Python3 (3.13.1 + numpy 2.2.1 + scipy 1.14.1) |
結果 |
AC
|
実行時間 | 712 ms / 2,000 ms |
コード長 | 37,502 bytes |
コンパイル時間 | 509 ms |
コンパイル使用メモリ | 16,384 KB |
実行使用メモリ | 43,028 KB |
最終ジャッジ日時 | 2024-06-28 06:22:50 |
合計ジャッジ時間 | 14,833 ms |
ジャッジサーバーID (参考情報) |
judge1 / judge5 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 3 |
other | AC * 41 |
ソースコード
import bisectfrom collections import defaultdictimport sysreadline=sys.stdin.readlineclass Graph:def __init__(self,V,edges=False,graph=False,directed=False,weighted=False,inf=float("inf")):self.V=Vself.directed=directedself.weighted=weightedself.inf=infif not graph:self.edges=edgesself.graph=[[] for i in range(self.V)]if weighted:for i,j,d in self.edges:self.graph[i].append((j,d))if not self.directed:self.graph[j].append((i,d))else:for i,j in self.edges:self.graph[i].append(j)if not self.directed:self.graph[j].append(i)else:self.graph=graphself.edges=[]for i in range(self.V):if self.weighted:for j,d in self.graph[i]:if self.directed or not self.directed and i<=j:self.edges.append((i,j,d))else:for j in self.graph[i]:if self.directed or not self.directed and i<=j:self.edges.append((i,j))def SIV_BFS(self,s,bfs_tour=False,bipartite_graph=False,linked_components=False,parents=False,unweighted_dist=False,weighted_dist=False):seen=[False]*self.Vseen[s]=Trueif bfs_tour:bt=[s]if linked_components:lc=[s]if parents:ps=[None]*self.Vif unweighted_dist or bipartite_graph:uwd=[self.inf]*self.Vuwd[s]=0if weighted_dist:wd=[self.inf]*self.Vwd[s]=0queue=deque([s])while queue:x=queue.popleft()for y in self.graph[x]:if self.weighted:y,d=yif not seen[y]:seen[y]=Truequeue.append(y)if bfs_tour:bt.append(y)if linked_components:lc.append(y)if parents:ps[y]=xif unweighted_dist or bipartite_graph:uwd[y]=uwd[x]+1if weighted_dist:wd[y]=wd[x]+dif bipartite_graph:bg=[[],[]]for tpl in self.edges:i,j=tpl[:2] if self.weighted else tplif uwd[i]==self.inf or uwd[j]==self.inf:continueif not uwd[i]%2^uwd[j]%2:bg=Falsebreakelse:for x in range(self.V):if uwd[x]==self.inf:continuebg[uwd[x]%2].append(x)retu=()if bfs_tour:retu+=(bt,)if bipartite_graph:retu+=(bg,)if linked_components:retu+=(lc,)if parents:retu+=(ps,)if unweighted_dist:retu+=(uwd,)if weighted_dist:retu+=(wd,)if len(retu)==1:retu=retu[0]return retudef MIV_BFS(self,initial_vertices=False,bipartite_graph=False,linked_components=False,parents=False):if not initial_vertices:initial_vertices=[i for i in range(self.V)]seen=[False]*self.Vif bipartite_graph:bg=[None]*self.Vcnt=-1if linked_components:lc=[]if parents:ps=[None]*self.Vfor s in initial_vertices:if seen[s]:continueseen[s]=Trueif bipartite_graph:cnt+=1bg[s]=(cnt,0)if linked_components:lc.append([s])queue=deque([s])while queue:x=queue.popleft()for y in self.graph[x]:if self.weighted:y,d=yif not seen[y]:seen[y]=Truequeue.append(y)if bipartite_graph:bg[y]=(cnt,bg[x][1]^1)if linked_components:lc[-1].append(y)if parents:ps[y]=xif bipartite_graph:bg_=bgbg=[[[],[]] for i in range(cnt+1)]for tpl in self.edges:i,j=tpl[:2] if self.weighted else tplif not bg_[i][1]^bg_[j][1]:bg[bg_[i][0]]=Falsefor x in range(self.V):if bg[bg_[x][0]]:bg[bg_[x][0]][bg_[x][1]].append(x)retu=()if bipartite_graph:retu+=(bg,)if linked_components:retu+=(lc,)if parents:retu=(ps,)if len(retu)==1:retu=retu[0]return retudef SIV_DFS(self,s,bipartite_graph=False,cycle_detection=False,directed_acyclic=False,euler_tour=False,linked_components=False,parents=False,postorder=False,preorder=False,subtree_size=False,topological_sort=False,unweighted_dist=False,weighted_dist=False):seen=[False]*self.Vfinished=[False]*self.Vif directed_acyclic or cycle_detection or topological_sort:dag=Trueif euler_tour:et=[]if linked_components:lc=[]if parents or cycle_detection or subtree_size:ps=[None]*self.Vif postorder or topological_sort:post=[]if preorder:pre=[]if subtree_size:ss=[1]*self.Vif unweighted_dist or bipartite_graph:uwd=[self.inf]*self.Vuwd[s]=0if weighted_dist:wd=[self.inf]*self.Vwd[s]=0stack=[(s,0)] if self.weighted else [s]while stack:if self.weighted:x,d=stack.pop()else:x=stack.pop()if not seen[x]:seen[x]=Truestack.append((x,d) if self.weighted else x)if euler_tour:et.append(x)if linked_components:lc.append(x)if preorder:pre.append(x)for y in self.graph[x]:if self.weighted:y,d=yif not seen[y]:stack.append((y,d) if self.weighted else y)if parents or cycle_detection or subtree_size:ps[y]=xif unweighted_dist or bipartite_graph:uwd[y]=uwd[x]+1if weighted_dist:wd[y]=wd[x]+delif not finished[y]:if (directed_acyclic or cycle_detection or topological_sort) and dag:dag=Falseif cycle_detection:cd=(y,x)elif not finished[x]:finished[x]=Trueif euler_tour:et.append(~x)if postorder or topological_sort:post.append(x)if subtree_size:for y in self.graph[x]:if self.weighted:y,d=yif y==ps[x]:continuess[x]+=ss[y]if bipartite_graph:bg=[[],[]]for tpl in self.edges:i,j=tpl[:2] if self.weighted else tplif uwd[i]==self.inf or uwd[j]==self.inf:continueif not uwd[i]%2^uwd[j]%2:bg=Falsebreakelse:for x in range(self.V):if uwd[x]==self.inf:continuebg[uwd[x]%2].append(x)retu=()if bipartite_graph:retu+=(bg,)if cycle_detection:if dag:cd=[]else:y,x=cdcd=self.Route_Restoration(y,x,ps)retu+=(cd,)if directed_acyclic:retu+=(dag,)if euler_tour:retu+=(et,)if linked_components:retu+=(lc,)if parents:retu+=(ps,)if postorder:retu+=(post,)if preorder:retu+=(pre,)if subtree_size:retu+=(ss,)if topological_sort:if dag:tp_sort=post[::-1]else:tp_sort=[]retu+=(tp_sort,)if unweighted_dist:retu+=(uwd,)if weighted_dist:retu+=(wd,)if len(retu)==1:retu=retu[0]return retudef MIV_DFS(self,initial_vertices=False,bipartite_graph=False,cycle_detection=False,directed_acyclic=False,euler_tour=False,linked_components=False,parents=False,postorder=False,preorder=False,subtree_size=False,topological_sort=False,unweighted_dist=False,weighted_dist=False):if not initial_vertices:initial_vertices=[s for s in range(self.V)]seen=[False]*self.Vfinished=[False]*self.Vif bipartite_graph:bg=[None]*self.Vcnt=-1if directed_acyclic or cycle_detection or topological_sort:dag=Trueif euler_tour:et=[]if linked_components:lc=[]if parents or cycle_detection or subtree_size:ps=[None]*self.Vif postorder or topological_sort:post=[]if preorder:pre=[]if subtree_size:ss=[1]*self.Vif unweighted_dist:uwd=[self.inf]*self.Vif weighted_dist:wd=[self.inf]*self.Vfor s in initial_vertices:if seen[s]:continueif bipartite_graph:cnt+=1bg[s]=(cnt,0)if linked_components:lc.append([])if unweighted_dist:uwd[s]=0if weighted_dist:wd[s]=0stack=[(s,0)] if self.weighted else [s]while stack:if self.weighted:x,d=stack.pop()else:x=stack.pop()if not seen[x]:seen[x]=Truestack.append((x,d) if self.weighted else x)if euler_tour:et.append(x)if linked_components:lc[-1].append(x)if preorder:pre.append(x)for y in self.graph[x]:if self.weighted:y,d=yif not seen[y]:stack.append((y,d) if self.weighted else y)if bipartite_graph:bg[y]=(cnt,bg[x][1]^1)if parents or cycle_detection or subtree_size:ps[y]=xif unweighted_dist or bipartite_graph:uwd[y]=uwd[x]+1if weighted_dist:wd[y]=wd[x]+delif not finished[y]:if directed_acyclic and dag:dag=Falseif cycle_detection:cd=(y,x)elif not finished[x]:finished[x]=Trueif euler_tour:et.append(~x)if postorder or topological_sort:post.append(x)if subtree_size:for y in self.graph[x]:if self.weighted:y,d=yif y==ps[x]:continuess[x]+=ss[y]if bipartite_graph:bg_=bgbg=[[[],[]] for i in range(cnt+1)]for tpl in self.edges:i,j=tpl[:2] if self.weighted else tplif not bg_[i][1]^bg_[j][1]:bg[bg_[i][0]]=Falsefor x in range(self.V):if bg[bg_[x][0]]:bg[bg_[x][0]][bg_[x][1]].append(x)retu=()if bipartite_graph:retu+=(bg,)if cycle_detection:if dag:cd=[]else:y,x=cdcd=self.Route_Restoration(y,x,ps)retu+=(cd,)if directed_acyclic:retu+=(dag,)if euler_tour:retu+=(et,)if linked_components:retu+=(lc,)if parents:retu+=(ps,)if postorder:retu+=(post,)if preorder:retu+=(pre,)if subtree_size:retu+=(ss,)if topological_sort:if dag:tp_sort=post[::-1]else:tp_sort=[]retu+=(tp_sort,)if unweighted_dist:retu+=(uwd,)if weighted_dist:retu+=(wd,)if len(retu)==1:retu=retu[0]return retudef Tree_Diameter(self,weighted=False):def Farthest_Point(u):dist=self.SIV_BFS(u,weighted_dist=True) if weighted else self.SIV_BFS(u,unweighted_dist=True)fp=0for i in range(self.V):if dist[fp]<dist[i]:fp=ireturn fp,dist[fp]u,d=Farthest_Point(0)v,d=Farthest_Point(u)return u,v,ddef SCC(self):reverse_graph=[[] for i in range(self.V)]for tpl in self.edges:i,j=tpl[:2] if self.weighted else tplreverse_graph[j].append(i)postorder=self.MIV_DFS(postorder=True)scc=[]seen=[False]*self.Vfor s in postorder[::-1]:if seen[s]:continuequeue=deque([s])seen[s]=Truelst=[]while queue:x=queue.popleft()lst.append(x)for y in reverse_graph[x]:if self.weighted:y,d=yif not seen[y]:seen[y]=Truequeue.append(y)scc.append(lst)return sccdef Build_LCA(self,s):self.lca_euler_tour,self.lca_parents,depth=self.SIV_DFS(s,euler_tour=True,parents=True,unweighted_dist=True)self.lca_dfs_in_index=[None]*self.Vself.lca_dfs_out_index=[None]*self.Vfor i,x in enumerate(self.lca_euler_tour):if x>=0:self.lca_dfs_in_index[x]=ielse:self.lca_dfs_out_index[~x]=iself.ST=Segment_Tree(2*self.V,lambda x,y:min(x,y),self.V)lst=[None]*(2*self.V)for i in range(2*self.V-1):if self.lca_euler_tour[i]>=0:lst[i]=depth[self.lca_euler_tour[i]]else:lst[i]=depth[self.lca_parents[~self.lca_euler_tour[i]]]lst[2*self.V-1]=-1self.ST.Build(lst)def LCA(self,a,b):m=min(self.lca_dfs_in_index[a],self.lca_dfs_in_index[b])M=max(self.lca_dfs_in_index[a],self.lca_dfs_in_index[b])x=self.lca_euler_tour[self.ST.Fold_Index(m,M+1)]if x>=0:return xelse:return self.lca_parents[~x]def Build_HLD(self,s):self.hld_parents,size,self.hld_depth=self.SIV_DFS(s,parents=True,subtree_size=True,unweighted_dist=True)stack=[s]self.hld_tour=[]self.hld_path_parents=[None]*self.Vself.hld_path_parents[s]=swhile stack:x=stack.pop()self.hld_tour.append(x)max_size=0max_size_y=Nonefor y in self.graph[x]:if self.weighted:y,d=yif y==self.hld_parents[x]:continueif max_size<size[y]:max_size=size[y]max_size_y=yfor y in self.graph[x]:if self.weighted:y,d=yif y==self.hld_parents[x]:continueif y!=max_size_y:stack.append(y)self.hld_path_parents[y]=yif max_size_y!=None:stack.append(max_size_y)self.hld_path_parents[max_size_y]=self.hld_path_parents[x]self.hld_tour_idx=[None]*self.Vfor i in range(self.V):self.hld_tour_idx[self.hld_tour[i]]=idef HLD(self,a,b,edge=False):L,R=[],[]while self.hld_path_parents[a]!=self.hld_path_parents[b]:if self.hld_depth[self.hld_path_parents[a]]<self.hld_depth[self.hld_path_parents[b]]:R.append((self.hld_tour_idx[self.hld_path_parents[b]],self.hld_tour_idx[b]+1))b=self.hld_parents[self.hld_path_parents[b]]else:L.append((self.hld_tour_idx[a]+1,self.hld_tour_idx[self.hld_path_parents[a]]))a=self.hld_parents[self.hld_path_parents[a]]if edge:if self.hld_depth[a]!=self.hld_depth[b]:retu=L+[(self.hld_tour_idx[a]+1,self.hld_tour_idx[b]+1)]+R[::-1]else:retu=L+R[::-1]else:if self.hld_depth[a]<self.hld_depth[b]:retu=L+[(self.hld_tour_idx[a],self.hld_tour_idx[b]+1)]+R[::-1]else:retu=L+[(self.hld_tour_idx[a]+1,self.hld_tour_idx[b])]+R[::-1]return retudef Build_Hash(self,s,random_number=False,mod=(1<<61)-1,rerooting=False):self.bottom_hash=[None]*self.Vif random_number:self.hash_random_number=random_numberelse:self.hash_random_number=[random.randint(1,10**10) for i in range(self.V)]self.hash_mod=modparents,postorder,preorder=self.SIV_DFS(s,parents=True,postorder=True,preorder=True)for x in postorder:level=0for y in self.graph[x]:if self.weighted:y,d=yif y==parents[x]:continueh,l=self.bottom_hash[y]level=max(level,l+1)ha=1for y in self.graph[x]:if self.weighted:y,d=yif y==parents[x]:continueh,l=self.bottom_hash[y]ha*=h+self.hash_random_number[l]ha%=self.hash_modself.bottom_hash[x]=(ha,level)if rerooting:self.top_hash=[None]*self.Vself.top_hash[s]=(1,-1)for x in preorder:children=[y for y,d in self.graph[x] if y!=parents[x]] if self.weighted else [y for y in self.graph[x] if y!=parents[x]]if children:l=len(children)l_lst,r_lst=[None]*(l+1),[None]*(l+1)l_lst[0],r_lst[l]=(1,-1),(1,-1)for i in range(1,l+1):h0,l0=l_lst[i-1]h1,l1=self.bottom_hash[children[i-1]]l_lst[i]=(h0*(h1+self.hash_random_number[l1])%self.hash_mod,max(l0,l1))for i in range(l-1,-1,-1):h0,l0=r_lst[i+1]h1,l1=self.bottom_hash[children[i]]r_lst[i]=(h0*(h1+self.hash_random_number[l1])%self.hash_mod,max(l0,l1))for i in range(l):if x==s:ha,level=1,0else:ha,level=self.top_hash[x]h0,l0=l_lst[i]h1,l1=r_lst[i+1]ha*=h0*h1level=max(level,l0+1,l1+1)ha+=self.hash_random_number[level]ha%=self.hash_modlevel+=1self.top_hash[children[i]]=(ha,level)returndef Hash(self,root,subtree=False):if subtree:ha,level=self.bottom_hash[root]ha+=self.hash_random_number[level]ha%=self.hash_modelse:h0,l0=self.bottom_hash[root]h1,l1=self.top_hash[root]ha=(h0*h1+self.hash_random_number[max(l0,l1)])%self.hash_modlevel=max(l0,l1)return ha,leveldef Centroid(self,root=0):x=rootparents,size=self.SIV_DFS(x,parents=True,subtree_size=True)while True:for y in self.graph[x]:if self.weighted:y,d=yif y==parents[x]:continueif size[y]*2>size[root]:x=ybreakelse:for y in self.graph[x]:if y==parents[x]:continueif size[root]<=2*size[y]:return x,yreturn x,Nonedef Centroid_Decomposition(self,edge=False,linked_point=False,point=False,tree=False):if edge:cd_edges_lst=[None]*self.Vif linked_point:cd_linked_points=[None]*self.Vif point:cd_points_lst=[None]*self.Vif tree:cd_tree=[]*self.Vif self.weighted:edges=[(i,j) for i,j,d in self.edges]else:edges=self.edgespoints=[i for i in range(self.V)]prev_centroid=Nonestack=[(edges,points,None,prev_centroid)] if linked_point else [(edges,points,prev_centroid)]while stack:if linked_point:edges,points,lp,prev_centroid=stack.pop()else:edges,points,prev_centroid=stack.pop()if len(points)==1:centroid=points[0]if edge:cd_edges_lst[centroid]=[]if linked_point:cd_linked_points[centroid]=lpif point:cd_points_lst[centroid]=[centroid]if tree and prev_centroid!=None:cd_tree.append((prev_centroid,centroid))continueG=Graph(len(points),edges=edges)centroid,_=G.Centroid()if tree and prev_centroid!=None:cd_tree.append((prev_centroid,points[centroid]))parents,tour=G.SIV_DFS(centroid,parents=True,preorder=True)dp=[None]*len(points)edges_lst=[]points_lst=[]if linked_point:linked_points=[]for i,x in enumerate(G.graph[centroid]):dp[x]=(i,0)edges_lst.append([])points_lst.append([points[x]])if linked_point:linked_points.append(points[x])for x in tour[1:]:for y in G.graph[x]:if y==parents[x]:continuei,j=dp[x]jj=len(points_lst[i])edges_lst[i].append((j,jj))points_lst[i].append(points[y])dp[y]=(i,jj)centroid=points[centroid]if edge:cd_edges_lst[centroid]=edgesif linked_point:cd_linked_points[centroid]=lpif point:cd_points_lst[centroid]=pointsif linked_point:for edges,points,lp in zip(edges_lst,points_lst,linked_points):stack.append((edges,points,lp,centroid))else:for edges,points in zip(edges_lst,points_lst):stack.append((edges,points,centroid))retu=()if edge:retu+=(cd_edges_lst,)if linked_point:retu+=(cd_linked_points,)if point:retu+=(cd_points_lst,)if tree:retu+=(cd_tree,)if len(retu)==1:retu=retu[0]return retudef Distance_Frequency(self):mod=206158430209cnt=[0]*Ncd_edges,cd_lp,cd_points,cd_tree=self.Centroid_Decomposition(edge=True,linked_point=True,point=True,tree=True)CD=Graph(N,edges=cd_tree)parents,tour=CD.SIV_DFS(cd_tree[0][0],parents=True,postorder=True)for x in tour:C=[0]*(len(cd_points[x])+1)for y in CD.graph[x]:if y==parents[x]:continuedepth=Graph(len(cd_points[y]),edges=cd_edges[y]).SIV_DFS(0,unweighted_dist=True)CC=[0]*(max(depth)+2)for d in depth:CC[d+1]+=1cnt[d+1]+=2C[d+1]+=1poly=NTT_Pow(CC,2)for d,c in enumerate(poly):if d<N:cnt[d]-=cwhile C and C[-1]==0:C.pop()poly=NTT_Pow(C,2)for d,c in enumerate(poly):if d<N:cnt[d]+=cfor i in range(N):cnt[i]//=2return cntdef Dijkstra(self,s,route_restoration=False):dist=[self.inf]*self.Vdist[s]=0hq=[(0,s)]if route_restoration:parents=[None]*self.Vwhile hq:dx,x=heapq.heappop(hq)if dist[x]<dx:continuefor y,dy in self.graph[x]:if dist[y]>dx+dy:dist[y]=dx+dyif route_restoration:parents[y]=xheapq.heappush(hq,(dist[y],y))if route_restoration:return dist,parentselse:return distdef Bellman_Ford(self,s,route_restoration=False):dist=[self.inf]*self.Vdist[s]=0if route_restoration:parents=[None]*self.Vfor _ in range(self.V-1):for i,j,d in self.edges:if dist[j]>dist[i]+d:dist[j]=dist[i]+dif route_restoration:parents[j]=iif not self.directed and dist[i]>dist[j]+d:dist[i]=dist[j]+dif route_restoration:parents[i]=jnegative_cycle=[]for i,j,d in self.edges:if dist[j]>dist[i]+d:negative_cycle.append(j)if not self.directed and dist[i]>dist[j]+d:negative_cycle.append(i)if negative_cycle:is_negative_cycle=[False]*self.Vfor i in negative_cycle:if is_negative_cycle[i]:continueelse:queue=deque([i])is_negative_cycle[i]=Truewhile queue:x=queue.popleft()for y,d in self.graph[x]:if not is_negative_cycle[y]:queue.append(y)is_negative_cycle[y]=Trueif route_restoration:parents[y]=xfor i in range(self.V):if is_negative_cycle[i]:dist[i]=-self.infif route_restoration:return dist,parentselse:return distdef Warshall_Floyd(self,route_restoration=False):dist=[[self.inf]*self.V for i in range(self.V)]for i in range(self.V):dist[i][i]=0if route_restoration:parents=[[j for j in range(self.V)] for i in range(self.V)]for i,j,d in self.edges:if i==j:continueif dist[i][j]>d:dist[i][j]=dif route_restoration:parents[i][j]=iif not self.directed and dist[j][i]>d:dist[j][i]=dif route_restoration:parents[j][i]=jfor k in range(self.V):for i in range(self.V):for j in range(self.V):if dist[i][j]>dist[i][k]+dist[k][j]:dist[i][j]=dist[i][k]+dist[k][j]if route_restoration:parents[i][j]=parents[k][j]for i in range(self.V):if dist[i][i]<0:for j in range(self.V):if dist[i][j]!=self.inf:dist[i][j]=-self.infif route_restoration:for i in range(self.V):if dist[i][i]==0:parents[i][i]=Nonereturn dist,parentselse:return distdef Route_Restoration(self,s,g,parents):route=[g]while s!=g:if parents[g]==None:route=[]breakg=parents[g]route.append(g)route=route[::-1]return routedef Kruskal(self):UF=UnionFind(self.V)sorted_edges=sorted(self.edges,key=lambda x:x[2])minimum_spnning_tree=[]for i,j,d in sorted_edges:if not UF.Same(i,j):UF.Union(i,j)minimum_spnning_tree.append((i,j,d))return minimum_spnning_treedef Ford_Fulkerson(self,s,t):max_flow=0residual_graph=[defaultdict(int) for i in range(self.V)]if self.weighted:for i,j,d in self.edges:if not d:continueresidual_graph[i][j]+=dif not self.directed:residual_graph[j][i]+=delse:for i,j in self.edges:residual_graph[i][j]+=1if not self.directed:residual_graph[j][i]+=1while True:parents=[None]*self.Vparents[s]=sseen=[False]*self.Vseen[s]=Truequeue=deque([s])while queue:x=queue.popleft()for y in residual_graph[x].keys():if not seen[y]:seen[y]=Truequeue.append(y)parents[y]=xif y==t:tt=twhile tt!=s:residual_graph[parents[tt]][tt]-=1residual_graph[tt][parents[tt]]+=1if not residual_graph[parents[tt]][tt]:residual_graph[parents[tt]].pop(tt)tt=parents[tt]max_flow+=1breakelse:continuebreakelse:breakreturn max_flowdef BFS(self,s):seen=[False]*self.Vseen[s]=Truequeue=deque([s])while queue:x=queue.popleft()for y in self.graph[x]:if self.weighted:y,d=yif not seen[y]:seen[y]=Truequeue.append(y)returndef DFS(self,s):seen=[False]*self.Vfinished=[False]*self.Vstack=[(s,0)] if self.weighted else [s]while stack:if self.weighted:x,d=stack.pop()else:x=stack.pop()if not seen[x]:seen[x]=Truestack.append((x,d) if self.weighted else x)for y in self.graph[x]:if self.weighted:y,d=yif not seen[y]:stack.append((y,d) if self.weighted else y)elif not finished[x]:finished[x]=Truereturnclass Cumsum:def __init__(self,lst,mod=0):self.N=len(lst)self.mod=modself.cumsum=[0]*(self.N+1)self.cumsum[0]=0for i in range(1,self.N+1):self.cumsum[i]=self.cumsum[i-1]+lst[i-1]if self.mod:self.cumsum[i]%=self.moddef __getitem__(self,i):if type(i)==int:if 0<=i<self.N:a,b=i,i+1elif -self.N<=i<0:a,b=i+self.N,i+self.N+1else:raise IndexError('list index out of range')else:a,b=i.start,i.stopif a==None or a<-self.N:a=0elif self.N<=a:a=self.Nelif a<0:a+=self.Nif b==None or self.N<=b:b=self.Nelif b<-self.N:b=0elif b<0:b+=self.Ns=self.cumsum[b]-self.cumsum[a]if self.mod:s%=self.modreturn sdef __setitem__(self,i,x):if -self.N<=i<0:i+=self.Nelif not 0<=i<self.N:raise IndexError('list index out of range')self.cumsum[i+1]=self.cumsum[i]+xif self.mod:self.cumsum[i+1]%=self.moddef __str__(self):lst=[self.cumsum[i+1]-self.cumsum[i] for i in range(self.N)]if self.mod:for i in range(self.N):lst[i]%=self.modreturn "["+", ".join(map(str,lst))+"]"class Prime:def __init__(self,N):assert N<=10**8self.smallest_prime_factor=[None]*(N+1)for i in range(2,N+1,2):self.smallest_prime_factor[i]=2n=int(N**.5)+1for p in range(3,n,2):if self.smallest_prime_factor[p]==None:self.smallest_prime_factor[p]=pfor i in range(p**2,N+1,2*p):if self.smallest_prime_factor[i]==None:self.smallest_prime_factor[i]=pfor p in range(n,N+1):if self.smallest_prime_factor[p]==None:self.smallest_prime_factor[p]=pself.primes=[p for p in range(N+1) if p==self.smallest_prime_factor[p]]def Factorize(self,N):assert N>=1factors=defaultdict(int)if N<=len(self.smallest_prime_factor)-1:while N!=1:factors[self.smallest_prime_factor[N]]+=1N//=self.smallest_prime_factor[N]else:for p in self.primes:while N%p==0:N//=pfactors[p]+=1if N<p*p:if N!=1:factors[N]+=1breakif N<=len(self.smallest_prime_factor)-1:while N!=1:factors[self.smallest_prime_factor[N]]+=1N//=self.smallest_prime_factor[N]breakelse:if N!=1:factors[N]+=1return factorsdef Divisors(self,N):assert N>0divisors=[1]for p,e in self.Factorize(N).items():A=[1]for _ in range(e):A.append(A[-1]*p)divisors=[i*j for i in divisors for j in A]return divisorsdef Is_Prime(self,N):return N==self.smallest_prime_factor[N]def Totient(self,N):for p in self.Factorize(N).keys():N*=p-1N//=preturn Ndef Mebius(self,N):fact=self.Factorize(N)for e in fact.values():if e>=2:return 0else:if len(fact)%2==0:return 1else:return -1N=int(readline())edges=[]for _ in range(N-1):A,B=map(int,readline().split())A-=1;B-=1edges.append((A,B))G=Graph(N,edges=edges)parents,size=G.SIV_DFS(0,parents=True,subtree_size=True)ans=0for x in range(N):ans+=N**2lst=[]for y in G.graph[x]:if y==parents[x]:continuelst.append(size[y])if x:lst.append(N-1-sum(lst))for s in lst:ans-=s**2print(ans)