洛谷P4017 最大食物链计数(拓扑排序)

原题链接

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#define ll long long
#include
using namespace std;
inline ll read() {
    ll k = 0, f = 1; char ch = getchar();
    while (ch < '0' || ch>'9') { if (ch == '-')f = -1; ch = getchar(); }
    while (ch >= '0' && ch <= '9') { k = k * 10 + ch - '0'; ch = getchar(); }return k * f;
}
ll mod = 80112002;
vector<ll>v1[5005];
ll in[5005], out[5005];
ll ans[5005];
int main()
{
    ll n=read(), m=read();
    for (int i = 0; i < m; i++)
    {
        ll u = read(), v = read();
        v1[u].push_back(v);
        out[u]++, in[v]++;
    }
    queue<ll>q;
    for (int i = 1; i <= n; i++)
    {
        if (in[i] == 0)
        {
            q.push(i);
            ans[i] = 1;
        }
    }
    while (!q.empty())
    {
        ll temp = q.front();
        q.pop();
        for (int i = 0; i < v1[temp].size(); i++)
        {
            ll now = v1[temp][i];
            in[now]--;
            if (in[now] == 0)q.push(now);
            ans[now] = (ans[now] + ans[temp]) % mod;
        }
    }
    ll o = 0;
    for (int i = 1; i <= n; i++)
    {
        if (out[i] == 0)
        {
            o = (o + ans[i]) % mod;
        }
    }
    cout << o << '\n';
}

你可能感兴趣的:(洛谷P4017 最大食物链计数(拓扑排序))