Cod sursa(job #751072)

Utilizator deividFlorentin Dumitru deivid Data 24 mai 2012 09:04:33
Problema Ciclu Eulerian Scor 80
Compilator cpp Status done
Runda Arhiva educationala Marime 1.41 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,e;
int Used[maxn],E[maxm],Gr[maxn],viz[maxn];
vector< pair<int,int> >G[maxn];
stack<int>St;

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

void dfs ( int nod ){
	viz[nod] = 1;
	for ( int i = 0 ; i < G[nod].size() ; ++i ){
		int nodvcn = G[nod][i].first;
		if ( !viz[nodvcn] ){
			dfs(nodvcn);
		}
	}
}

inline void euler () {
	
	int nod_s = 0;
	for ( int i = 1 ; i <= n ; ++i ){
		if ( Gr[i] ){
			dfs(i); nod_s = i;
			break ;
		}
	}
	
	for ( int 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() ){
		int nod = St.top();
		
		if ( G[nod].empty() ){
			E[++e] = nod; St.pop();
		}
		else{
			int nodvcn = G[nod][G[nod].size()-1].first;
			int index = G[nod][G[nod].size()-1].second;
			
			if ( Used[index] ){
				G[nod].pop_back();
			}
			else{
				St.push(nodvcn);
				Used[index] = 1;
			}
		}
	}
	
	for ( int i = 1 ; i < e ; ++i ){
		fprintf(g,"%d ",E[i]);
	}
	fprintf(g,"\n");
}

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