1 条题解

  • 0
    @ 2025-10-8 16:50:25

    D01 拓扑排序

    #include<bits/stdc++.h>
    using namespace std;
    const int N=110;
    vector<int>G[N],ans;
    int n,din[N];
    bool toposort()
    {
    	priority_queue<int,vector<int>,greater<int>>q;
    	for(int i=1;i<=n;i++)if(din[i]==0)q.push(i);
    	while(!q.empty())
    	{
    		int x=q.top();q.pop();
    		ans.push_back(x);
    		for(int y:G[x])
    			if( --din[y]==0) q.push(y);
    	}
    	return ans.size()==n;
    }
    int main()
    {
        while( scanf("%d",&n)!=EOF) 
        {
            memset(G,0,sizeof(G));ans.clear();
            memset(din,0,sizeof(din));
            for(int i=1;i<=n;i++)
            {
                int k;scanf("%d",&k);
                for(int j=1; j<=k; j++)
                {
                    int x;scanf("%d",&x);
                    G[i].push_back(x);
                    din[x]++;
                }
            }
            if( !toposort() ){puts("No answer.");continue;}
            else
            {
                for(int x:ans) printf("%d ",x);
                printf("\n");
            }
        }
        return 0;
    }
    
    • 1

    D01*【拓扑(难度:3)】大学选课

    信息

    ID
    407
    时间
    1000ms
    内存
    128MiB
    难度
    6
    标签
    递交数
    185
    已通过
    64
    上传者