记忆化搜索水过去了……

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;
}

 

相关文章:

  • 2021-11-05
  • 2021-06-13
  • 2022-12-23
  • 2021-04-03
  • 2021-08-24
  • 2022-12-23
猜你喜欢
  • 2021-06-23
  • 2021-07-22
  • 2021-05-26
  • 2021-11-23
  • 2021-11-27
相关资源
相似解决方案