Pagini recente » Cod sursa (job #1586522) | Cod sursa (job #2861151) | Cod sursa (job #1718989) | Cod sursa (job #1592901) | Cod sursa (job #1424697)
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>
#define MAX 100002
using namespace std;
ifstream f("ciclueuler.in" , ios::in) ;
ofstream g ( "ciclueuler.out", ios ::out );
vector < int > arc [ MAX ] ;
int viz [ MAX ] ;
unsigned int n;
void sterge_muchie( unsigned int x, unsigned int y )
{
unsigned int i;
arc [ x ].pop_back();
for ( i = 0 ; i < arc [ y ].size() ; i++)
if ( arc [ y ] [ i ] == x )
{
arc [ y ].erase ( arc [ y ].begin() + i ) ;
break;
}
}
bool euler ( int node)
{
unsigned int i, top_node , sol ;
stack < unsigned int > stiva ;
stiva.push ( node );
while ( !stiva.empty() ){
top_node = stiva.top() ;
if ( arc [ top_node ].size() ){
stiva.push ( arc [ top_node].back() );
sterge_muchie ( top_node , arc [ top_node ].back() );
}
else{
if(stiva.size() != 1) // ca sa nu afisez ultima comp ; asa e in cerinta
g<<stiva.top()<<" ";
stiva.pop() ;
}
}
}
bool dfs(){
int top_node,node = 1 ;
unsigned int i ;
stack <unsigned int > st ;
bool contor ;
st.push ( node );
viz [ node ] = 1;
while ( ! st.empty() ){
contor = 0;
top_node = st.top();
for ( i = 0 ; i < arc [ top_node ].size() ; i++)
if ( viz [ arc [ top_node ] [ i ] ] == 0 )
{
contor = 1;
st.push ( arc [ top_node ] [ i ] ) ;
viz [ arc [ top_node ] [ i ] ] = 1;
break ;
}
//daca nodul nu mai are niciun vecin nevizitat facem pop
if(!contor)
st.pop();
}
// daca a ramas un nod nevizitat atunci graful nu e conex
for ( i = 1; i <= n ; i++)
if( viz[ i ] == 0 )
return 0;
return 1 ;
}
bool isEulerian ( ){
unsigned int i ;
// paritatea gradelor
for ( i = 1 ; i <= n ; i++ )
if ( arc [ i ].size() % 2 )
return 0 ;
//conexitate
return dfs( ) ;
}
int main()
{
unsigned int x,y ,m,i;
f>>n>>m;
while ( m ){
m--;
f>>x>>y;
arc [ x ].push_back ( y );
arc [ y ]. push_back ( x );
}
/*ca sa admita un ciclu eurelian graful trebuie sa fie conex iar gradele tuturor nodurilor sa fie pare */
if( isEulerian())
{
euler ( 1 );
}
else
g<<"-1";
g.close();
f.close();
return 0;
}