Cod sursa(job #631324)

Utilizator floringh06Florin Ghesu floringh06 Data 7 noiembrie 2011 20:05:49
Problema Ciclu Eulerian Scor 80
Compilator cpp Status done
Runda Arhiva educationala Marime 2.51 kb
#include <map>
#include <set>
#include <stack>
#include <queue>
#include <algorithm>
#include <sstream>
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <climits>
#include <cfloat>
#include <numeric>

using namespace std;

const int    oo  = 0x3f3f3f3f;
const double eps = 1e-9;

typedef long long ll;
typedef vector<int> vi;
typedef vector<string> vs;
typedef pair<int, int> pii;

#define sz(c) int ((c).size())
#define all(c) (c).begin(), (c).end()
#define FOR(i, a, b) for (int i = (a); i < (b); ++i)
#define FORD(i, a, b) for (int i = (b) - 1; i >= (a); --i)
#define FORIT(i, c) for (__typeof__((c).begin()) i = (c).begin(); i != (c).end(); ++i)
#define mp make_pair
#define pb push_back
#define MAX_N 100005

vector<pii> adj[MAX_N];

vi path;
int pos[MAX_N];
bool used[MAX_N * 5];
int N, M;

int position;
stack<int> st;

void rek (int start) {
     st.push(start);
     while (!st.empty()) {
          int n = st.top(); 
           
          if (pos[n] < sz(adj[n])) {
             while (pos[n] < sz(adj[n])) {
                 int p = pos[n]++;
                 if (!used[adj[n][p].second]) {
                     used[adj[n][p].second] = true;
                     
                     st.push(adj[n][p].first);
                     break;
                 } 
             }
          } else {
             path[position++] = n;
             st.pop();
          }
     }
}

bool euler_path() {
     //path.clear();
     memset (pos, 0, sizeof (pos));
     memset (used, 0, sizeof (used));
     int nodd = 0, st = -1;
     FOR (i, 0, N) {
         if (sz(adj[i]) == 0) continue;
         if (st == -1) st = i;
         if (sz(adj[i]) % 2) { nodd++; st = i; }
     }
     if (nodd != 0 && nodd != 2) return false;
     if (st == -1) return true;
     rek (st);
     return position == M + 1;
}

int main () {
    freopen ("ciclueuler.in", "r", stdin);
    freopen ("ciclueuler.out", "w", stdout);
    
    scanf ("%d %d", &N, &M);
    FOR (i, 0, M) {
        int x, y;
        scanf ("%d %d", &x, &y);
        
        --x, --y;
        adj[x].pb(mp(y, i));
        adj[y].pb(mp(x, i));
    }
    
    path = vector<int>(M + 1);
    if (!euler_path()) printf ("-1\n");
       else {
            path.pop_back();
            FOR (i, 0, sz(path)) 
                if (i == sz(path) - 1) printf ("%d\n", path[i] + 1);
                   else printf ("%d ", path[i] + 1);
       }
    
    return 0;
}