Cod sursa(job #754724)

Utilizator visanrVisan Radu visanr Data 2 iunie 2012 23:36:58
Problema Ciclu Eulerian Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.32 kb
#include <vector>
#include <stack>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <cstring>
using namespace std;

#define nmax 100010

vector<int> G[nmax];
vector<int> sol;
int n, m, x, y;

void read_input()
{
     scanf("%i %i\n", &n, &m);
     char s[15];
     bool ok = false;
     for(int i = 0; i < m; i++)
     {
              ok = false;
              fgets(s, 15, stdin);
              int lg = strlen(s) - 1;
              x = 0; y = 0;
              for(int j = 0; j < lg; j++)
              {
                       if(s[j] == ' ') ok = true;
                       else
                       {
                           if(ok == false) x = x * 10 + s[j] - '0';
                           else y = y * 10 + s[j] - '0';
                       }
              }
              G[x].push_back(y);
              G[y].push_back(x);
     }
}

bool Eulerian()
{
     for(int i = 1; i <= n; i++) if(G[i].size() % 2) return false;
     return true;
}

void euler()
{
     int node;
     stack <int> s;
     s.push(1);
     while(!s.empty())
     {
                      node = s.top();
                      if(G[node].size() == 0)
                      {
                                        sol.push_back(node);
                                        s.pop();
                      }else
                      {
                           int last = G[node].back();
                           G[node].pop_back();
                           s.push(last);
                           for(int i = 0; i < G[last].size(); i++)
                           {
                                 if(G[last][i] == node)
                                 {
                                               G[last][i] = G[last].back();
                                               G[last].pop_back();
                                               break;
                                 }
                           }
                      }     
     }
     for(int i = 0; i < sol.size() - 1; i++) printf("%i ", sol[i]);
     printf("\n");
}

int main()
{
    freopen("ciclueuler.in", "r", stdin);
    freopen("ciclueuler.out", "w", stdout);
    int i;
    read_input();
    if(Eulerian() == true) euler();
    else printf("-1\n");
    scanf("%i", &i);
    return 0;
}