tyvj1202 数数食物链

描述

TsyD学习了生物的生态环境那一张后,老师留了一项作业,就是给一张食物网,求所有食物链的总数。(从最低营养级生物(它不能吃任何其他的生物)开始到最高营养级(它不能被任何其他生物吃) 叫做一条食物链)
输入保证所有的生物之间都有直接或间接的生存关系

输入格式

第一行 N,M 分别表示有N(N<=50000)个生物,M(M<=100000)个吃的关系
接下来M行 每行有两个值a,b 分别 表示b吃a (编号从1开始)

输出格式

食物链的总数 MOD 11129 的值

测试样例1

输入

3 3 
1 2 
2 3 
1 3

输出

2

备注

样例解释:
两条食物链分别为 1->3
 1->2->3
#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<algorithm>
#include<vector>
using namespace std;
const int maxn = 100005,mod = 11129;
vector<int> g[maxn];
int n,m,f[maxn],topo[maxn],cnt,ans;
bool vis[maxn],ind[maxn];
void input(){
    scanf("%d%d",&n,&m);
    int a,b;
    for(int i = 1;i <= m;i++){
        scanf("%d%d",&a,&b);
        g[a].push_back(b);
        ind[b] = true;
    }
}
void topo_dfs(int x){
    vis[x] = true;
    for(int i = 0;i < g[x].size();i++){
        if(!vis[g[x][i]]) topo_dfs(g[x][i]);
    }
    topo[cnt--] = x;
}
void topo_sort(){
    cnt = n;
    for(int i = 1;i <= n;i++){
        if(!vis[i]) topo_dfs(i);
    }
}
void dfs(int x){
    if(!g[x].size()){
        f[x] = 1;
        return;
    }
    for(int i = 0;i < g[x].size();i++){
        if(!f[g[x][i]]) dfs(g[x][i]);
        f[x] = (f[x] + f[g[x][i]]) % mod;
    }
}
void dp(){
    for(int i = 1;i <= n;i++){
        if(!f[topo[i]]) dfs(topo[i]);
        if(!ind[topo[i]]) ans = (ans + f[topo[i]]) % mod;
    }
    cout<<ans;
}
int main(){
    input();
    topo_sort();
    dp();
    return 0;
}

 

posted @ 2016-08-09 21:19  ACforever  阅读(213)  评论(0编辑  收藏  举报