結果
問題 | No.2949 Product on Tree |
ユーザー | lif4635 |
提出日時 | 2024-10-25 21:35:50 |
言語 | PyPy3 (7.3.15) |
結果 |
AC
|
実行時間 | 752 ms / 2,000 ms |
コード長 | 3,306 bytes |
コンパイル時間 | 272 ms |
コンパイル使用メモリ | 82,036 KB |
実行使用メモリ | 187,416 KB |
最終ジャッジ日時 | 2024-10-25 21:36:25 |
合計ジャッジ時間 | 33,598 ms |
ジャッジサーバーID (参考情報) |
judge4 / judge5 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 3 |
other | AC * 46 |
ソースコード
#int-input def II() -> int : return int(input()) def MI() -> int : return map(int, input().split()) class fenwick_tree(): n=1 data=[0 for i in range(n)] def __init__(self,N): self.n=N self.data=[0 for i in range(N)] def add(self,p,x): assert 0<=p<self.n,"0<=p<n,p={0},n={1}".format(p,self.n) p+=1 while(p<=self.n): self.data[p-1]+=x p+=p& -p def sum(self,l,r): assert (0<=l and l<=r and r<=self.n),"0<=l<=r<=n,l={0},r={1},n={2}".format(l,r,self.n) return self.sum0(r)-self.sum0(l) def sum0(self,r): s=0 while(r>0): s+=self.data[r-1] r-=r&-r return s class dsu(): n=1 parent_or_size=[-1 for i in range(n)] def __init__(self,N): self.n=N self.parent_or_size=[-1 for i in range(N)] def merge(self,a,b): assert 0<=a<self.n, "0<=a<n,a={0},n={1}".format(a,self.n) assert 0<=b<self.n, "0<=b<n,b={0},n={1}".format(b,self.n) x=self.leader(a) y=self.leader(b) if x==y: return x if (-self.parent_or_size[x]<-self.parent_or_size[y]): x,y=y,x self.parent_or_size[x]+=self.parent_or_size[y] self.parent_or_size[y]=x return x def same(self,a,b): assert 0<=a<self.n, "0<=a<n,a={0},n={1}".format(a,self.n) assert 0<=b<self.n, "0<=b<n,b={0},n={1}".format(b,self.n) return self.leader(a)==self.leader(b) def leader(self,a): assert 0<=a<self.n, "0<=a<n,a={0},n={1}".format(a,self.n) if (self.parent_or_size[a]<0): return a self.parent_or_size[a]=self.leader(self.parent_or_size[a]) return self.parent_or_size[a] def size(self,a): assert 0<=a<self.n, "0<=a<n,a={0},n={1}".format(a,self.n) return -self.parent_or_size[self.leader(a)] def groups(self): leader_buf=[0 for i in range(self.n)] group_size=[0 for i in range(self.n)] for i in range(self.n): leader_buf[i]=self.leader(i) group_size[leader_buf[i]]+=1 result=[[] for i in range(self.n)] for i in range(self.n): result[leader_buf[i]].append(i) result2=[] for i in range(self.n): if len(result[i])>0: result2.append(result[i]) return result2 n = II() a = list(MI()) edge = [set() for i in range(n)] for i in range(n-1): u,v = MI() u -= 1 v -= 1 edge[u].add(v) edge[v].add(u) mod = 998244353 def DFS_par(edge): #親の情報をうまく持つDFS ans = 0 cnt = [0]*len(edge) #親を持ちながら非再帰DFS n = len(edge) st = [(0,None,0)] while st: # print(cnt) now,par,t = st.pop() if t == 0: st.append((now,par,1)) #行きがけ for chi in edge[now]: if chi != par: st.append((chi,now,0)) else: ans += cnt[now]*a[now]%mod if par != None: tmp = a[now]*(cnt[now]+1)%mod ans += cnt[par]*a[par]*tmp%mod cnt[par] += tmp pass #帰りがけ return ans print(DFS_par(edge)%mod)