洛谷P3183 [HAOI2016]食物链

洛谷P3183 [HAOI2016]食物链
记忆化搜索

 

 1 #include <bits/stdc++.h> 
 2 #define For(i,j,k) for(int i=j;i<=k;i++) 
 3 using namespace std ; 
 4 
 5 const int N = 100011,M = 200011 ; 
 6 int n,m,cnt,ans ; 
 7 int f[N],head[N],IN[N],OUT[N] ; 
 8 struct node{
 9     int to,pre ; 
10 }e[M] ; 
11 
12 inline int read() 
13 {
14     int x = 0 , f = 1 ; 
15     char ch = getchar() ; 
16     while(ch<'0'||ch>'9') { if(ch=='-') f = -1 ; ch = getchar() ; } 
17     while(ch>='0'&&ch<='9') { x = x * 10+ch-48 ; ch = getchar() ; } 
18     return x * f ;  
19 }
20 
21 inline void add(int x,int y) 
22 {
23     e[++cnt].to = y ; 
24     e[cnt].pre = head[x] ; 
25     head[x] = cnt ; 
26 }
27 
28 inline int dfs(int u) 
29 {
30     if(f[u]) return f[u] ; 
31     if(IN[u]&&!OUT[u]) return f[u] = 1 ;          //  单个生物是无法成为食物链的 
32     for(int i=head[u];i;i=e[i].pre) {
33         int v = e[i].to ;  
34         f[u]+=dfs(v) ;  
35     }
36     return f[u] ; 
37 }
38 
39 int main() 
40 {
41     n = read() ; m = read() ; 
42     int x,y ; 
43     while(m--) {
44         x = read() ; y = read() ; 
45         add(x,y) ; OUT[x]++ ; IN[y]++ ; 
46     }
47     For(i,1,n) if(!f[i]) ans+=dfs(i) ; 
48     printf("%d\n",ans) ; 
49     return 0 ; 
50 }

 

转载于:https://www.cnblogs.com/third2333/p/7525940.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值