【bzoj4562】HAOI2016食物链

记忆化搜索水过去了……

QwQ

#include<bits/stdc++.h>
#define N 400010
typedef long long ll;
using namespace std;
int head[4*N],tot=0,in[N],out[N],n,m;
struct Edge{int u,v,next;}G[N<<1];
inline void addedge(int u,int v){
    G[++tot].u=u;G[tot].v=v;G[tot].next=head[u];head[u]=tot;
}
ll dp[N];
ll dfs(int u){
    if(dp[u])return dp[u];ll ans=0;
    if(!out[u]&&in[u])++ans;
    for(int i=head[u];i;i=G[i].next){
        int v=G[i].v;ans+=dfs(v);
    }
    dp[u]=ans;return ans;
}
inline int read(){
    int f=1,x=0;char ch;
    do{ch=getchar();if(ch=='-')f=-1;}while(ch<'0'||ch>'9');
    do{x=x*10+ch-'0';ch=getchar();}while(ch>='0'&&ch<='9');
    return f*x;
}
int main(){
    n=read();m=read();
    for(int i=1,u,v;i<=m;i++){
        u=read();v=read();out[u]++;in[v]++;
        addedge(u,v);
    }
    ll ans=0;
    for(int i=1;i<=n;i++)if(!in[i])ans+=dfs(i);
    cout<<ans<<endl;
}

 

posted @ 2017-06-12 17:28  zcysky  阅读(185)  评论(0编辑  收藏  举报