标签:des style blog http color io os java ar
2 2 1 2 3 1 2 2 3
2 6
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <cmath> #include <string> #include <map> #include <stack> #include <vector> #include <set> #include <queue> #pragma comment (linker,"/STACK:102400000,102400000") #define maxn 2000005 #define MAXN 4000005 #define INF 0x3f3f3f3f #define mod 1000000007 #define eps 1e-6 const double pi=acos(-1.0); typedef long long ll; using namespace std; int n,m,cnt; int head[maxn],num[maxn]; ll dp[maxn],inv[maxn],fac[maxn],ans; struct node { int v,next; } edge[MAXN]; void addedge(int u,int v) { cnt++; edge[cnt].v=v; edge[cnt].next=head[u]; head[u]=cnt; } void egcd(ll a,ll b,ll &x,ll &y) { if(b==0) { x=1,y=0; return ; } egcd(b,a%b,x,y); ll t=x; x=y; y=t-a/b*x; } void presolve() { int i; fac[0]=1; for(i=1; i<=1000000; i++) { ll x,y; fac[i]=(fac[i-1]*i)%mod; egcd(fac[i],mod,x,y); x=(x+mod)%mod; inv[i]=x; } } void dfs1(int u,int fa) { num[u]=dp[u]=1; int i,v; for(i=head[u]; i; i=edge[i].next) { v=edge[i].v; if(v==fa) continue ; dfs1(v,u); num[u]+=num[v]; dp[u]=(dp[v]*dp[u])%mod; dp[u]=(dp[u]*inv[num[v]])%mod; } dp[u]=(dp[u]*fac[num[u]-1])%mod; } void dfs2(int u,int fa) { int i,v; if(u!=1) { ll x,y; egcd(n-num[u],mod,x,y); dp[u]=((dp[fa]*num[u])%mod*x)%mod; } ans=(ans+(dp[u]*dp[u]))%mod; for(i=head[u]; i; i=edge[i].next) { v=edge[i].v; if(v==fa) continue ; dfs2(v,u); } } int main() { int i,j,t; presolve(); scanf("%d",&t); while(t--) { scanf("%d",&n); cnt=0; memset(head,0,sizeof(head)); int u,v; for(i=1; i<n; i++) { scanf("%d%d",&u,&v); addedge(u,v); addedge(v,u); } dfs1(1,0); ans=0; dfs2(1,0); printf("%I64d\n",ans); } return 0; }
hdu 4661 Message Passing (思维 dp求拓扑排序数)
标签:des style blog http color io os java ar
原文地址:http://blog.csdn.net/tobewhatyouwanttobe/article/details/39318791