Luogu P4017 Maximum Food Chain Count (Graph Theory-Topological Sorting)

Insert picture description here

Ideas:

  • Record the out-degree and in-degree of each side input.
  • Then traverse the in-degree of each point, store the points whose in-degree is zero into the queue, and set the f (the number of food chains array) corresponding to the point whose in-degree is zero to 1.
  • Then start to perform BFS on the queue and update the number of food chains at the point at the same time. Finally, when the in and out degree of a point is 0, the number of food chains is recorded in ans.

Code:

#include <iostream>
#include<algorithm>
#include<queue>
using namespace std;
int n,m;
int G[5005][5005];
int ru[5005],chu[5005];
int f[5005];
int MOD=80112002;
int ans=0;
queue<int> q;
int main() {
    
    
    cin>>n>>m;
    for(int i=0;i<m;i++){
    
    
        int u,v;
        cin>>u>>v;
        G[u][v]=1;
        ru[v]++;
        chu[u]++;
    }
    for(int i=1;i<=n;i++)
    {
    
    
        if(ru[i]==0)
        {
    
    
            q.push(i);
            f[i]=1;
        }
    }
    while(!q.empty()){
    
    
        int cur=q.front();
        q.pop();
        for(int i=1;i<=n;i++)
        {
    
    
            if(G[cur][i]==1)
            {
    
    
                f[i]+=f[cur];
                f[i]%=MOD;
                ru[i]--;
                if(ru[i]==0)
                {
    
    
                    if(chu[i]==0)
                    {
    
    
                        ans+=f[i];
                        ans%=MOD;
                        continue;
                    }
                    q.push(i);
                }
            }
        }
    }
    cout<<ans<<endl;
}

Guess you like

Origin blog.csdn.net/qq_43663263/article/details/108076977