1 条题解

  • 0
    @ 2025-12-7 14:45:11
    #include<bits/stdc++.h>
    using namespace std;
    const int N=1e6+10;
    #define PII pair<int,int>
    vector<PII>G[N];
    stack<PII>stk;int v[N],instk[N];
    void dfs(int x)
    {
    	if(instk[x])
    	{
    		int z=-1;deque<int>q;
    		while(z!=x)
    		{
    			int y=stk.top().second;z=stk.top().first;stk.pop();
    			q.push_front(y-1);
    		}
    		cout<<q.size()<<'\n';
    		for(int i:q)cout<<i<<'\n';
    		exit(0);
    	}
    	if(v[x])return;v[x]=1;
    	for(auto i:G[x])
    	{
    		int y=i.first,w=i.second;
    		stk.push({x,w});instk[x]=1;
    		dfs(y);
    		stk.pop();instk[x]=0;
    	}
    }
    int main()
    {
    	int n,m;cin>>n>>m;
    	for(int i=1;i<=m;i++)
    	{
    		int x,y;cin>>x>>y;x++,y++;
    		G[x].push_back({y,i});
    	}
    	for(int i=1;i<=n;i++)if(!v[i])
    	{
    		while(!stk.empty())stk.pop();
    		dfs(i);
    	}
    	puts("-1");
    	return 0;
    }
    
    • 1

    有向图环检测(Cycle Detection (Directed))

    信息

    ID
    8159
    时间
    500ms
    内存
    1024MiB
    难度
    8
    标签
    递交数
    59
    已通过
    11
    上传者