Cod sursa(job #2112578)

Utilizator Horia14Horia Banciu Horia14 Data 23 ianuarie 2018 17:27:22
Problema Ciclu Eulerian Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.26 kb
#include<cstdio>
#include<vector>
#include<stack>
#include<cctype>
#define MAX_N 100000
#define BUF_SIZE 1 << 18
using namespace std;

struct node {
    int val;
    node* next;
};

node* g[MAX_N + 1];

vector<int>sol;
stack<int>st;
int degree[MAX_N + 1], n, m, pos = BUF_SIZE;
char buf[BUF_SIZE];

char getChar(FILE *fin) {
    if(pos == BUF_SIZE) {
        fread(buf,1,BUF_SIZE,fin);
        pos = 0;
    }
    return buf[pos++];
}

inline int read(FILE *fin) {
    int res = 0;
    char ch;
    do {
        ch = getChar(fin);
    }while(!isdigit(ch));
    do {
        res = 10*res + ch - '0';
        ch = getChar(fin);
    }while(isdigit(ch));
    return res;
}

inline void insertElem(int x, int y) {
    node* elem = new node;
    elem->val = y;
    elem->next = g[x];
    g[x] = elem;
}

void readGraph() {
    int x, y;
    FILE *fin = fopen("ciclueuler.in","r");
    n = read(fin); m = read(fin);
    for(int i = 0; i < m; i++) {
        x = read(fin); y = read(fin);
        insertElem(x,y);
        insertElem(y,x);
        degree[x]++;
        degree[y]++;
    }
    fclose(fin);
}

bool isEulerian() {
    bool ok = true;
    for(int i = 1; i <= n && ok; i++)
        if(degree[i] & 1)
            ok = false;
    return ok;
}

node* deleteNode(node* head, int val) {
    node* p, *q;
    if(head->val == val) {
        p = head;
        head = head->next;
        delete p;
    } else {
        q = head;
        while(q->next->val != val)
            q = q->next;
        p = q->next;
        q->next = q->next->next;
        delete p;
    }
    return head;
}

void Euler(int u) {
    int v;
    st.push(u);
    while(!st.empty()) {
        u = st.top();
        if(g[u] != NULL) {
            v = g[u]->val;
            g[u] = deleteNode(g[u],v);
            g[v] = deleteNode(g[v],u);
            st.push(v);
        } else {
            st.pop();
            sol.push_back(u);
        }
    }
}

void printEulerianCycle() {
    int k;
    FILE *fout = fopen("ciclueuler.out","w");
    if(isEulerian()) {
        Euler(1);
        k = sol.size();
        for(int i = 0; i < k - 1; i++)
            fprintf(fout,"%d ",sol[i]);
        fprintf(fout,"\n");
    } else {
        fprintf(fout,"-1\n");
    }
    fclose(fout);
}

int main() {
    readGraph();
    printEulerianCycle();
    return 0;
}