Cod sursa(job #742335)

Utilizator visanrVisan Radu visanr Data 29 aprilie 2012 16:10:48
Problema Ciclu Eulerian Scor 80
Compilator cpp Status done
Runda Arhiva educationala Marime 2.23 kb
#include <vector>
#include <stack>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <cstring>
using namespace std;

#define nmax 100010

vector<int> graph[nmax];
vector<int> solution;
int n,m,x,y;

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

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

void euler(int start)
{
     stack <int> s;
     s.push(start);
     int node,nextNode;
     while(!s.empty())
     {
                      node=s.top();
                      while(!graph[node].empty())
                      {
                                                 nextNode= *graph[node].begin();
                                                 graph[nextNode].erase(find(graph[nextNode].begin(),graph[nextNode].end(),node));
                                                 graph[node].erase(graph[node].begin());
                                                 s.push(nextNode);
                                                 node=nextNode;
                      }
                      solution.push_back(s.top());
                      s.pop();
     }
     solution.pop_back();
     for(vector<int>::iterator it=solution.begin();it!=solution.end();++it) printf("%i ", *it);
     printf("\n");
}

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