962F - Simple Cycles Edges - CodeForces Solution


dfs and similar graphs trees *2400

Please click on ads to support us..

C++ Code:

#include<bits/stdc++.h>
#define int long long
using namespace std;
#define min(a,b) (a<b?a:b)
const int N=5e5+5;
int dfn[N],low[N],m,n,tot,root,cnt;
stack<int>stk,stk2;
bool cut[N],vis[N];
vector<int>dcc[N];
vector<pair<int,int> >nbr[N];
#define fi first
#define se second
#define mp make_pair 
void tarjan(int cur,int ID){
	dfn[cur]=low[cur]=++tot;
	stk.push(cur);
	if(cur==root&&nbr[cur].empty()){
		dcc[++cnt].push_back(cur);
		return;
	}
	int flag=0;
	for(auto x:nbr[cur]){
		int to=x.fi,id=x.se;
		if(!dfn[to]){
			stk2.push(id);
			tarjan(to,id);
			low[cur]=min(low[cur],low[to]);
			if(low[to]>=dfn[cur]){
				++flag;
				if(root!=cur&&flag>1)cut[cur]=1;
				++cnt;
				int x=0,num=1,num2=0;
				while(!stk.empty()&&x!=to){
					x=stk.top();
					dcc[cnt].push_back(x);
					num++;
					stk.pop();
				}
				dcc[cnt].push_back(cur);
				x=0;
				queue<int>q;
				while(!stk2.empty()){
					x=stk2.top();
					q.push(x);
					stk2.pop();
					num2++;
					if(x==id)break;
				}
				if(num==num2){
					while(!q.empty()){
						vis[q.front()]=1;
						q.pop();
					}
				}
			}
		}
		else{
			if(dfn[cur]>dfn[to]&&id!=ID)stk2.push(id);
			low[cur]=min(low[cur],dfn[to]);
		}
	}
	return;
} 
signed main(){
	ios::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0); 
	cin>>n>>m;
	for(int i=1;i<=m;++i){
		int u,v;
		cin>>u>>v;
		if(u==v)continue;
		nbr[u].push_back(mp(v,i));
		nbr[v].push_back(mp(u,i));
	}
	for(int i=1;i<=n;++i)if(!dfn[i])root=i,tarjan(i,0);
	int sum=0;
	for(int i=1;i<=m;++i)if(vis[i])sum++;
	cout<<sum<<'\n';
	for(int i=1;i<=m;++i)if(vis[i])cout<<i<<' ';
	return 0;
}
 	 			 	  		  	   	 			 	 	 	 	


Comments

Submit
0 Comments
More Questions

797. All Paths From Source to Target
1547B - Alphabetical Strings
1550A - Find The Array
118B - Present from Lena
27A - Next Test
785. Is Graph Bipartite
90. Subsets II
1560A - Dislike of Threes
36. Valid Sudoku
557. Reverse Words in a String III
566. Reshape the Matrix
167. Two Sum II - Input array is sorted
387. First Unique Character in a String
383. Ransom Note
242. Valid Anagram
141. Linked List Cycle
21. Merge Two Sorted Lists
203. Remove Linked List Elements
733. Flood Fill
206. Reverse Linked List
83. Remove Duplicates from Sorted List
116. Populating Next Right Pointers in Each Node
145. Binary Tree Postorder Traversal
94. Binary Tree Inorder Traversal
101. Symmetric Tree
77. Combinations
46. Permutations
226. Invert Binary Tree
112. Path Sum
1556A - A Variety of Operations