Skip to content

Instantly share code, notes, and snippets.

@chinchila
Created July 18, 2018 23:03
Show Gist options
  • Save chinchila/a0b4f41f1f13fd49f8f94bb21c4f8dee to your computer and use it in GitHub Desktop.
Save chinchila/a0b4f41f1f13fd49f8f94bb21c4f8dee to your computer and use it in GitHub Desktop.
Teamqueue(UVA 540) ansi c not so fast approach
/**
* UVA 540 resolution: https://uva.onlinejudge.org/index.php?option=onlinejudge&page=show_problem&problem=481
**/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_TEAMS 1001
#define MAX_ELEMENTS 1000001
#define MAX_COMMAND_BUFFER 255
#define free( n ) free( (void*) n ), n = NULL
typedef struct __queue_element__ {
int element;
struct __queue_element__ *next;
} QueueElement;
typedef struct __queue__ {
int size;
QueueElement *head;
QueueElement *tail;
} Queue;
Queue *queueList[MAX_TEAMS];
Queue *teamOrder;
int teams[MAX_ELEMENTS];
Queue *initQueue()
{
Queue *newQueue = malloc( sizeof( Queue ) );
newQueue->head = newQueue->tail = NULL;
newQueue->size = 0;
return newQueue;
}
void push( int element, Queue *queue )
{
QueueElement *queueElement = malloc( sizeof( QueueElement ) );
queueElement->element = element;
queueElement->next = NULL;
if( queue->head == NULL )
{
queue->tail = queue->head = queueElement;
}
else
{
queue->tail->next = queueElement;
queue->tail = queueElement;
}
++queue->size;
}
void enqueue( int element )
{
int team = teams[element];
if( queueList[team]->size == 0 )
{
push( team, teamOrder );
}
push( element, queueList[team] );
}
int pop( Queue *queue )
{
int element = -1;
if( queue->size != 0 )
{
QueueElement *elem = queue->head;
queue->head = elem->next;
element = elem->element;
free( elem );
--queue->size;
}
return element;
}
int dequeue()
{
int element = -1;
if( teamOrder->head != NULL )
{
int team = teamOrder->head->element;
element = pop( queueList[team] );
if( queueList[team]->size == 0 )
{
pop( teamOrder );
}
}
return element;
}
void clear()
{
while( dequeue() != -1 );
while( pop( teamOrder ) != -1 );
}
int
main()
{
int nTeams;
int currentScenario = 1;
char command[MAX_COMMAND_BUFFER];
teamOrder = initQueue();
int i = 0;
for( ; i < MAX_TEAMS ; ++i )
{
queueList[i] = initQueue();
}
scanf( "%d", &nTeams );
while( nTeams != 0 )
{
clear();
int i;
for( i = 0 ; i < nTeams ; ++i )
{
int nElements = 0;
scanf( "%d", &nElements );
while( nElements-- )
{
int element;
scanf( "%d", &element );
teams[element] = i;
}
}
printf( "Scenario #%d\n", currentScenario );
command[0] = '\0';
while( *command != 'S' )
{
if( *command == 'E' )
{
int element = 0;
scanf( "%d", &element );
enqueue( element );
}
else if ( *command == 'D' )
{
int element = dequeue();
printf( "%d\n", element );
}
scanf( "%s", command );
}
putchar( '\n' );
++currentScenario;
scanf( "%d", &nTeams );
}
clear();
free( teamOrder );
for( i = 0 ; i < MAX_TEAMS ; ++i )
{
free( queueList[i] );
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment