Submission #475437

#TimeUsernameProblemLanguageResultExecution timeMemory
475437MohamedAhmed04Pipes (CEOI15_pipes)C++14
70 / 100
5077 ms8932 KiB
#include <bits/stdc++.h>

using namespace std ;

const int MAX = 1e5 + 10 ;

int P[MAX] , sz[MAX] , P2[MAX] , mark[MAX] , dep[MAX] ;

int n , m ;

vector< vector<int> >adj(MAX) ;

void init()
{
	for(int i = 1 ; i <= n ; ++i)
		P[i] = i , sz[i] = 1 ;
}

int root(int node)
{
	if(P[node] == node)
		return node ;
	return root(P[node]) ;
}

void dfs(int node , int par , bool flag)
{
	for(auto &child : adj[node])
	{
		if(child == par)
			continue ;
		dep[child] = dep[node] + 1 ;
		if(P[node] == child)
			dfs(child , node , mark[node]) ;
		else
			dfs(child , node , mark[child]) ;
	}
	P[node] = P2[node] = par , mark[node] = flag ;
}

void Union(int x , int y)
{
	int a = root(x) ;
	int b = root(y) ;
	if(sz[a] < sz[b])
		swap(a , b) , swap(x , y) ;
	adj[x].push_back(y) , adj[y].push_back(x) ;
	dep[y] = dep[x] + 1 ; 
	dfs(y , x , 0) ;
	sz[a] += sz[b] ;
}

vector<int>v1 , v2 ;

void solve(int x , int y)
{
	while(x != y)
	{
		while(dep[x] >= dep[y] && x != y)
			v1.push_back(x) , mark[x] = 1 , x = P2[x] ;
		while(dep[y] >= dep[x] && x != y)
			v2.push_back(y) , mark[y] = 1 , y = P2[y] ;
	}
	for(auto &node : v1)
		P2[node] = x ;
	for(auto &node : v2)
		P2[node] = y ;
	v1.clear() , v2.clear() ;
}

int main()
{
	ios_base::sync_with_stdio(0) ;
	cin.tie(0) ;
	cin>>n>>m ;
	init() ;
	for(int i = 0 ; i < m ; ++i)
	{
		int x , y ;
		cin>>x>>y ;
		if(root(x) != root(y))
			Union(x , y) ;
		else
			solve(x , y) ;
	}
	for(int i = 1 ; i <= n ; ++i)
	{
		if(!mark[i] && P[i] != i)
			cout<<i<<" "<<P[i]<<"\n" ;
	}
	return 0 ;
}		
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...