Cod sursa(job #2093754)

Utilizator adireusadireus adireus Data 24 decembrie 2017 13:44:45
Problema Ciclu Eulerian Scor 80
Compilator c Status done
Runda Arhiva educationala Marime 2.3 kb
#include <stdlib.h>
#include <stdio.h>

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


int list_add_front(struct node **head, int val)
{
	struct node *tmp;
	tmp = malloc(sizeof(struct node));
	tmp->data = val;
	tmp->next = *head;
	*head = tmp;
	return 0;
}

int list_remove_front(struct node **head)
{
	struct node *tmp = *head;
	*head = (*head)->next;
	free(tmp);
	return 0;
}

int list_peek(struct node *head, int *val)
{
	*val = head->data;
	return 0;
}

int list_remove(struct node **head, int val)
{
	struct node **tmp;
	struct node *p;

	for (tmp = head; *tmp != NULL; tmp = &((*tmp)->next)) {
	 	if((*tmp)->data == val) {
			p = *tmp; 
			*tmp = (*tmp)->next;
			free(p);
			return 0;
		}
	}
	return 0;
}

int stack_push (struct node **head, int val)
{	
	return list_add_front(head, val);
}
int stack_pop (struct node **head)
{
	return list_remove_front(head);
	
}

int stack_peek (struct node *head, int* val)
{
	return list_peek(head, val);
}

int stack_is_empty (struct node *head) {
	return (head == NULL);
}

int main()
{
	int n, m;
	FILE *infile, *outfile;
	int u, v, i;
	struct node *st_path = NULL, **list;
	struct node *sol = NULL;
	int curr, count = 0;	

	infile = fopen("ciclueuler.in", "r");
	outfile = fopen("ciclueuler.out", "w");

	fscanf(infile, "%d %d", &n, &m);

	list = malloc((n+1) * sizeof(struct node*));
	for (i = 0; i <=n; i++)
		list[i] = NULL;

	for (i = 0 ; i < m; i++) {
		fscanf(infile, "%d %d", &u, &v);
		list_add_front(&list[u], v);
		list_add_front(&list[v], u);
	}

	stack_push(&st_path, 1);
	curr = 1;

	while (!stack_is_empty(st_path)) {
		//while current has edges
		while (list[curr] != NULL) {
			list_peek(list[curr], &v);
			list_remove_front(&list[curr]);
			list_remove(&list[v], curr);
			curr = v;
			stack_push(&st_path, curr);
		}
		int val;
		stack_peek(st_path, &val);
		while (list[val] == NULL) {
			// don't print first elem again
			if(st_path->next != NULL) {
				stack_push(&sol, val);
				count++;
			}
			stack_pop(&st_path);
			if (stack_is_empty(st_path))
				break;
			stack_peek(st_path, &val);
		}
		// first node that still has unused edges
		curr = val;
	}
	if (count != m)
		fprintf(outfile, "%d", -1);
	else {
		int val;
		while (!stack_is_empty(sol)){
			stack_peek(sol, &val);
			fprintf(outfile, "%d ", val);
			stack_pop(&sol);
		}
	}
	fclose(outfile);
	fclose(infile);
	
}