Topological sorting -hihocoder1175

https://hihocoder.com/problemset/problem/1175

The main is to understand the concept of topological sort, is to find the total order to meet the partial order represented by the diagram there is to know, after this, you can direct simulation. Constantly looking into the degree of the 0-point add to the mix, into the adjacent points minus one degree. Repeat to not be added.

 

const int MAXN=(int)1e5+5,MOD=142857;
vector<int>e[MAXN];
int a[MAXN],head[MAXN],ind[MAXN],vis[MAXN];
void init(){
    memset(ind,0,sizeof(ind));
    memset(head,0,sizeof(head));
    
}
void solve(){
    init();
    int n,m,u,v,k,sum(0);
    cin>>n>>m>>k;
    for(int i=1;i<=k;i++){
        scanf("%d",&u);
        a[u]++;
    }
    for(int i=1;i<=m;i++){
        scanf("%d%d",&u,&v);
        e[u].push_back(v);
        ind[v]++;
    }
    queue<int>que;
    for(int i=1;i<=n;i++){
        if(!ind[i]){
        //    ind[i]--;
            que.push(i);
            vis[i]=1;
        }
    }
    while(!que.empty()){
        int tmp=que.front();
        //cout<<tmp<<" "<<a[tmp]<<endl;
        que.pop();
        sum=(sum+a[tmp])%MOD;
        for(int i=0;i<e[tmp].size();i++){
            if(!vis[e[tmp][i]]){
                ind[e[tmp][i]]--;
                a[e[tmp][i]]+=a[tmp];
                a[e[tmp][i]]%=MOD;
                if(!ind[e[tmp][i]]){
                    vis[e[tmp][i]]=1;
                    que.push(e[tmp][i]);
                }
            }
        }
        
    }
    cout<<sum<<endl;
}

 

Guess you like

Origin www.cnblogs.com/wengsy150943/p/10991165.html
Recommended