Cod sursa(job #782266)

Utilizator SebiSebiPirtoaca George Sebastian SebiSebi Data 26 august 2012 16:20:48
Problema Ciclu Eulerian Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.47 kb
#include<stdio.h>
#include<vector>
#include<stack>

#define maxn 100005
#define maxm 500005
#define pb push_back
#define mp make_pair

using namespace std;

FILE*f=fopen("ciclueuler.in","r");
FILE*g=fopen("ciclueuler.out","w");

int n,m,i,x,y,e,nod_s,nod;
int Gr[maxn],viz[maxn],used[maxm],E[maxm];
vector< pair<int,int> >G[maxn];
pair<int,int>edge;
stack<int>St;

inline void citire () {
	
	fscanf(f,"%d %d",&n,&m);
	
	for ( i = 1 ; i <= m ; ++i ){
		fscanf(f,"%d %d",&x,&y);
		G[x].pb(mp(y,i)); ++Gr[x];
		G[y].pb(mp(x,i)); ++Gr[y];
	}
}

void dfs ( int nod ){
	viz[nod] = 1;
	
	for ( vector< pair<int,int> >::iterator itt = G[nod].begin() ; itt != G[nod].end() ; ++itt ){
		if ( !viz[itt->first] )
			dfs(itt->first);
	}
}

inline void euler () {
	
	for ( i = 1 ; i <= n ; ++i ){
		if ( Gr[i] ){
			dfs(i); nod_s = i;
			break ;
		}
	}
	
	for ( i = 1 ; i <= n ; ++i ){
		if ( ( Gr[i] & 1 ) || (Gr[i] && !viz[i]) ){
			fprintf(g,"-1\n");
			return ;
		}
	}
	
	St.push(nod_s);
	
	while ( !St.empty() ){
		nod = St.top();
		
		if ( G[nod].empty() ){
			E[++e] = nod;
			St.pop();
		}
		else{
			edge = G[nod][G[nod].size()-1];
			if ( used[edge.second] ){
				G[nod].pop_back();
			}
			else{
				used[edge.second] = 1;
				St.push(edge.first);
			}
		}
	}
	
	for ( i = 1 ; i < e ; ++i ){
		fprintf(g,"%d ",E[i]);
	}
	fprintf(g,"\n");
}

int main () {
	
	citire();
	euler();
	
	fclose(f);
	fclose(g);
	
	return 0;
}