Untitled

mail@pastecode.io avatar
unknown
plain_text
13 days ago
1.9 kB
2
Indexable
Never
#include<iostream>
#include<vector>
using namespace std;

#define WHITE 0
#define GREY 1
#define BLACK 2

void dfs(int node, vector<int> adj[], vector<int>& s, vector<int>& f, vector<int>& dfstree, int& time, vector<int>& vis, vector<vector<int>>&tree, vector<vector<int>>&forward, vector<vector<int>>&back){
	time += 1;
	s[node] = time;
	vis[node] = GREY;
	dfstree.push_back(node);
	for(int v: adj[node]){
		if(vis[v] == WHITE){
			dfs(v, adj, s, f, dfstree, time, vis, tree, forward, back);
			tree.push_back({node, v});
		}
		else if(vis[v] == GREY){
			back.push_back({node, v});
		}
		else if(s[node] < s[v]){
			forward.push_back({node, v});
		}
			
	}
	vis[node] = BLACK;
	time += 1;
	f[node] = time;
}

int main(){
	cout<<"Enter no of vertices: ";
	int v;
	cin>>v;
	vector<int> adj[v];
	cout<<"Enter no. of edges: ";
	int e;
	cin>>e;
	for(int i = 0; i < e; i++){
		int a, b;
		cin>>a>>b;
		adj[a].push_back(b);
	}
	vector<int> s(v), f(v), dfstree;
	vector<int> vis(v, WHITE);
	vector<vector<int>> tree, forward, back;

	int time = 0;
	for(int i = 0; i < v; i++){
		if(vis[i] == WHITE){
			dfs(i, adj, s, f, dfstree, time, vis, tree, forward, back);
			dfstree.push_back(-1);
		}
	}
	
	for(int i = 0; i < v; i++){
		cout<<"("<<i<<" ,"<<s[i]<<" ,"<<f[i]<<")"<<endl;
	}
	cout<<"Spanning Tree"<<endl;
	for(int i = 0; i < dfstree.size(); i++){
		if(dfstree[i] != -1)
			cout<<dfstree[i];
		else if(dfstree[i] == -1)
			cout<<" ";
		if(dfstree[i] != -1 && i < dfstree.size() - 1 && dfstree[i+1] != -1)
			cout<<"->";
		
	}
	cout<<endl;
	cout<<"Tree Edges"<<endl;
	for(int i = 0; i < tree.size(); i++){
		cout<<tree[i][0]<<"->"<<tree[i][1]<<endl;
	}
	cout<<"Forward Edges"<<endl;
	for(int i = 0; i < forward.size(); i++){
		cout<<forward[i][0]<<"->"<<forward[i][1]<<endl;
	}
	cout<<"Back Edges"<<endl;
	for(int i = 0; i < back.size(); i++){
		cout<<back[i][0]<<"->"<<back[i][1]<<endl;
	}
	return 0;
}
	
Leave a Comment