P2290 [HNOI2004]树的计数

P2290 [HNOI2004]树的计数
prufer序列模板题

#include <iostream>
#include <cstdio>
#include <queue>
#include <algorithm>
#include <cmath>
#include <cstring>
#define inf 2147483647
#define N 1000010
#define p(a) putchar(a)
#define For(i,a,b) for(long long i=a;i<=b;++i)
//by war
//2019.8.26
using namespace std;
long long n,sum,flag,cnt,temp,ans;
long long a[N],prime[N],tot[N];
bool vis[N];
void in(long long &x){
    long long y=1;char c=getchar();x=0;
    while(c<'0'||c>'9'){if(c=='-')y=-1;c=getchar();}
    while(c<='9'&&c>='0'){ x=(x<<1)+(x<<3)+c-'0';c=getchar();}
    x*=y;
}
void o(long long x){
    if(x<0){p('-');x=-x;}
    if(x>9)o(x/10);
    p(x%10+'0');
}

void Euler(){
    for(long long i=2;i<=150;i++){
        if(!vis[i]) prime[++cnt]=i;
        for(long long j=1;j<=cnt&&i*prime[j]<=150;j++){
            vis[i*prime[j]]=1;
            if(i%prime[j]==0)
            break;
        }
    }
}

long long ksm(long long a,long long b){
    long long r=1;
    while(b>0){
        if(b&1) r*=a;
        a*=a;
        b>>=1;
    }
    return r;
}

signed main(){
    in(n);Euler();
    For(i,1,n){
        in(a[i]),sum+=a[i]-1;
        if(!a[i]) flag=1;
    }
    if(n==1&&flag){
        o(1); return 0;
    }
    if(sum!=n-2||flag){
        o(0); return 0;
    }
    For(i,2,n-2){
        temp=i;
        For(j,1,cnt)
            while(temp%prime[j]==0){
                tot[prime[j]]++;
                temp/=prime[j];
            }
    }
    For(i,1,n)
        For(j,2,a[i]-1){
            temp=j;
            For(k,1,cnt)
                while(temp%prime[k]==0){
                    tot[prime[k]]--;
                    temp/=prime[k];
                }
        }
    ans=1;
    For(i,1,cnt)
        ans*=ksm(prime[i],tot[prime[i]]);
    o(ans);
    return 0;
}

 

posted @ 2019-08-26 17:03  WeiAR  阅读(145)  评论(0编辑  收藏  举报