uva540 team queue

32146 단어
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAXN 1000000
#define LOCAL

typedef struct
node
{

struct
node * next;
int
data;
}
node;

typedef struct
team_node
{

node * head;
node * rear;
struct
team_node * next;
}
team_node;

int
team[ MAXN];
int
num_team;

void
init( team_node ** head);
void
enqueue( team_node ** head, team_node ** tail, int element);
int
search_team( int * team, int element);
int
dequeue( team_node ** head);

int
main ()
{

team_node * head = NULL;
team_node * tail = NULL;
int
num;
int
no;
int
i, j;
char
buf[ 10 ];
int
element;
int
tests = 0 ;

#ifndef LOCAL
freopen( "c://uva_in.txt" , "r" , stdin);
#endif

while
( scanf( "%d" , & num_team) && num_team != 0 )
{

memset( team, - 1 , sizeof ( team));

for
( i = 0 ; i < num_team; i++)
{

scanf( "%d" , & num);

for
( j = 0 ; j < num; j++)
{

scanf( "%d" , & no);
team[ no] = i;
}
}


head = ( team_node *) malloc( sizeof ( struct team_node));
init(& head);
tail = NULL;

printf( "Scenario #%d/n" , ++ tests);
while
( scanf( "%s" , buf) && strcmp( buf, "STOP" ) != 0 )
{

if
( strcmp( buf, "ENQUEUE" ) == 0 )
{

scanf( "%d" , & element);
enqueue(& head, & tail, element);
}
else
{

element = dequeue(& head);
printf( "%d/n" , element);
}
}

printf( "/n" );

}


return
0 ;
}


void
init( team_node ** head)
{
(*
head)-> next = NULL;
(*
head)-> head = (* head)-> rear = NULL;
}


void
enqueue( team_node ** head, team_node ** tail, int element)
{

team_node * p;
node * q;
int
team1, team2;
int
data;
int
flag;

if
((* head)-> next == NULL)
{

q = ( node *) malloc( sizeof ( struct node));
q-> data = element;
q-> next = NULL;

p = ( team_node *) malloc( sizeof ( struct team_node));
p-> next = NULL;
p-> head = p-> rear = ( node *) malloc( sizeof ( struct node));
p-> rear-> next = q;
p-> rear = q;

(*
head)-> next = p;
*
tail = p;
}
else
{

flag = 0 ;
p = (* head)-> next;

while
( p)
{

data = p-> head-> next-> data;
team1 = search_team( team, data);
team2 = search_team( team, element);

if
( team1 == team2)
{

q = ( node *) malloc( sizeof ( struct node));
q-> data = element;
q-> next = NULL;

p-> rear-> next = q;
p-> rear = q;

flag = 1 ;
break
;
}
else
p = p-> next;
}


if
(! flag)
{

q = ( node*) malloc( sizeof ( struct node));
q-> data = element;
q-> next = NULL;

p = ( team_node *) malloc( sizeof ( struct team_node));
p-> next = NULL;
p-> head = p-> rear = ( node *) malloc( sizeof ( struct node));
p-> rear-> next = q;
p-> rear = q;
(*
tail)-> next = p;
*
tail = p;
}
}
}



int
search_team( int * team, int element)
{

return
team[ element];
}


int
dequeue( team_node ** head)
{

team_node * p;
node * q;
int
data;

p = (* head)-> next;
q = p-> head-> next;
data = q-> data;
p-> head-> next = q-> next;
free( q);
if
( p-> rear == q)
{

p-> rear = p-> head;
(*
head)-> next = p-> next;
free( p-> rear);
free( p);
}


return
data;
}

좋은 웹페이지 즐겨찾기