bzoj4011 [HNOI2015]落忆枫音(拓扑序dp+容斥原理+朱刘算法)

大爷题解传送:http://blog.csdn.net/popoqqq/article/details/45194103

#include 
#include 
#include 
#include 
using namespace std;
#define ll long long
#define inf 0x3f3f3f3f
#define N 100010
#define mod 1000000007
inline int read(){
    int x=0,f=1;char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9') x=x*10+ch-'0',ch=getchar();
    return x*f;
}
int n,m,X,Y,in[N],du[N],ans=1,f[N],inv[N],h[N],num=0;
struct edge{
    int to,next;
}data[N<<1];
queue<int>q;
inline void add(int x,int y){
    data[++num].to=y;data[num].next=h[x];h[x]=num;in[y]++;
}
int main(){
//  freopen("a.in","r",stdin);
    n=read();m=read();X=read();Y=read();if(Y!=1) add(X,Y);
    for(int i=1;i<=m;++i){
        int x=read(),y=read();add(x,y);
    }memcpy(du,in,sizeof(in));
    for(int i=2;i<=n;++i) ans=(ll)ans*du[i]%mod;
    if(X==Y||Y==1){printf("%d\n",ans);return 0;}inv[1]=1;
    for(int i=2;i<=n;++i) inv[i]=(ll)(mod-mod/i)*inv[mod%i]%mod;
    f[Y]=(ll)ans*inv[du[Y]]%mod;
    q.push(1);q.push(Y);
    while(!q.empty()){
        int x=q.front();q.pop();
        for(int i=h[x];i;i=data[i].next){
            int y=data[i].to;if(y==Y) continue;
            f[y]=(f[y]+(ll)f[x]*inv[du[y]])%mod;
            if(--in[y]==0) q.push(y);
        }
    }ans-=f[X];if(ans<0) ans+=mod;else ans%=mod;
    printf("%d\n",ans);
    return 0;
}

你可能感兴趣的:(bzoj,容斥原理,拓扑排序)