显示代码纯文本
- #include <bits/stdc++.h>
- #define ll long long
- using namespace std;
- //typedef long long ll;
-
- ll const N=100010,mod=1e9+7;
- ll n,idx;
- ll res,w[N],siz[N];
- ll head[N],Next[N],ver[N],fat[N];
-
- ll mul(ll a,ll b){
- return (a*b)%mod;
- }
-
- void edge(ll a,ll b){
- Next[++idx]=head[a],head[a]=idx,ver[idx]=b;
- return;
- }
-
- void getSiz(ll p){
- siz[p]=w[p]%mod;
- for (ll i=head[p];i;i=Next[i]){
- getSiz(ver[i]);siz[p]+=siz[ver[i]],siz[p]%=mod;
- }
- return;
- }
-
- void getRes(ll p){
- ll s=siz[p];
- res+=mul(mul(w[p],w[p]),s*2-w[p]);
- for (ll i=head[p];i;i=Next[i]){
- res+=mul(mul(siz[ver[i]],s-siz[ver[i]]-w[p]),w[p]);
- getRes(ver[i]);
- }
- return;
- }
-
- int main(){
- freopen("asm_algo.in","r",stdin);
- freopen("asm_algo.out","w",stdout);
-
- ll pt;
- ll si;
- scanf("%d %lld",&n,&w[1]);
- for (ll i=2;i<=n;i++){
- scanf("%d %lld",&pt,&si);
- edge(pt,i);fat[i]=pt,w[i]=si;
- }
- getSiz(1);
- getRes(1);
- printf("%lld",res%mod);
-
- return 0;
- }