(懒得想了,,又是DP)
1 #include<bits/stdc++.h> 2 #define N 200005 3 #define LL long long 4 #define inf 0x3f3f3f3f 5 #define ls tr[x][0] 6 #define rs tr[x][1] 7 using namespace std; 8 inline int ra() 9 { 10 int x=0,f=1; char ch=getchar(); 11 while (ch<'0' || ch>'9') {if (ch=='-') f=-1; ch=getchar();} 12 while (ch>='0' && ch<='9') {x=x*10+ch-'0'; ch=getchar();} 13 return x*f; 14 } 15 const int mod=1e9+7; 16 vector<LL > G[N],L[N],R[N]; 17 LL dp[N],up[N]; 18 int n; 19 void dfsdown(int x, int fa) 20 { 21 dp[x]=1; 22 for (int i=0; i<G[x].size(); i++) 23 { 24 int v=G[x][i]; 25 if (v==fa) {L[x].push_back(1); R[x].push_back(1); continue;} 26 dfsdown(v,x); 27 L[x].push_back(dp[v]+1); 28 R[x].push_back(dp[v]+1); 29 dp[x]=dp[x]*(dp[v]+1)%mod; 30 } 31 for (int i=1; i<L[x].size(); i++) L[x][i]=L[x][i]*L[x][i-1]%mod; 32 for (int i=R[x].size()-2;i>=0; i--) R[x][i]=R[x][i]*R[x][i+1]%mod; 33 } 34 void dfsup(int x, int fa, int val) 35 { 36 up[x]=val; LL tem; 37 for (int i=0; i<G[x].size(); i++) 38 { 39 int v=G[x][i]; 40 tem=val; 41 if (v==fa) continue; 42 if (i>0) tem=tem*L[x][i-1]%mod; 43 if (i<G[x].size()-1) tem=tem*R[x][i+1]%mod; 44 dfsup(v,x,tem+1); 45 } 46 } 47 int main() 48 { 49 n=ra(); 50 for (int i=2; i<=n; i++) 51 { 52 int x=ra(); 53 G[x].push_back(i); 54 G[i].push_back(x); 55 } 56 dfsdown(1,0); dfsup(1,0,1); 57 for (int i=1; i<=n; i++) 58 printf("%I64d ",up[i]*dp[i]%mod); 59 }