12 exercícios · Livro III

A Última Travessia

Dicas e resoluções dos exercícios do capítulo 15 de Os Caminhos de Valdora.

Os enunciados preservam os identificadores da primeira edição. Abra cada resposta depois de tentar.

L3-C15-E01

Compreensão#

Fora do RPG: um sistema de atendimento usa fila de prioridade. Explique por que o algoritmo pode cumprir corretamente uma regra de prioridade e ainda aplicar uma política considerada injusta pelas pessoas afetadas.

Ver uma dica

Corretude da implementação é relativa à regra escolhida, não à legitimidade dessa regra.

Ver resolução comentada

Uma fila pode retirar exatamente a tarefa de menor número de prioridade e respeitar o desempate anunciado, mas os números podem ter sido definidos de modo discriminatório ou deixar um grupo esperando sempre. O algoritmo cumprir a política não demonstra que a política é justa. Critérios, participação, revisão e consequências precisam ser discutidos pelas pessoas responsáveis, além dos testes do código.

L3-C15-E02

Compreensão#

O projeto usa hash para itens, fila para comandos e grafo para rotas. Por que não é necessário acrescentar uma árvore de busca apenas porque ela foi estudada no livro?

Ver uma dica

Cada estrutura deve responder a uma necessidade do projeto.

Ver resolução comentada

Hash atende consulta exata de itens, fila preserva ordem dos comandos e grafo representa conexões. Acrescentar uma BST só para usar todo o conteúdo aumenta memória, manutenção e invariantes sem fornecer requisito novo. Ela faria sentido se uma necessidade de consultas por ordem/faixa justificasse seu custo e suas garantias, documentadas no projeto.

L3-C15-E03

Previsão#

Uma rota confirmada A–B é bloqueada antes de executar um comando de viagem já enfileirado. Qual validação deve ocorrer na execução e que informações devem ser preservadas quando a viagem for recusada?

Ver uma dica

O plano foi calculado antes da mudança; a execução usa o estado atual.

Ver resolução comentada

Revalide cadastro de cada posto, sequência origem/destino, disponibilidade de todas as arestas e autorização vigente antes de confirmar a viagem. Se AB ficou bloqueada, recuse sem mudar posição, recursos, status ou plano salvo e sem retirar definitivamente o comando. Preserve ID e destino do pedido para replanejamento explícito; não substitua silenciosamente a rota aceita por outra.

L3-C15-E04

Teste de mesa#

Fora do RPG: postos de atendimento A,B,C,D ligam-se por AB,BC e AD. Pedidos P1 para C e P2 para D chegam nessa ordem. Faça uma tabela de processamento FIFO e caminhos BFS a partir de A; não compare custos que não foram informados.

Ver uma dica

FIFO decide qual pedido é examinado primeiro; BFS calcula seu caminho sem pesos.

Ver resolução comentada
rodadapedidodestinocaminho a partir de Aarestas
1P1CA–B–C2
2P2DA–D1

A fila recebe P1 antes de P2 e conserva essa ordem. O caminho mais curto de P2 não o antecipa automaticamente. Os números são contagens de arestas, não dinheiro, tempo ou prioridade social.

L3-C15-E05

Teste de mesa#

No mapa AB,AC,BD,CD, feche BD após calcular A–B–D. Registre consulta inicial, bloqueio, tentativa recusada e nova consulta; use vizinhos alfabéticos e explique o novo caminho.

Ver uma dica

Uma consulta nova não apaga o plano anterior de um pedido já enfileirado.

Ver resolução comentada

Consulta inicial: A–B–D, pois B é examinado antes de C. Depois de fechar BD, a tentativa desse plano é recusada e conserva pedido/comando/plano. Uma nova BFS encontra A–C–D, também com duas arestas. O pedido só passa a usar essa rota após replanejamento explícito; então pode ser executado se suas arestas continuarem disponíveis.

L3-C15-E06

Teste de mesa#

Uma sessão cria três postos, duas arestas não dirigidas representadas por quatro nós, duas missões e uma fila de comandos. Liste blocos alocados por categoria e proponha uma ordem de destruição compatível com ponteiros emprestados.

Ver uma dica

Declare o modelo de alocação antes de contar blocos.

Ver resolução comentada

Modelo adotado: três postos alocados separadamente; quatro nós de adjacência para duas arestas não dirigidas; duas missões alocadas separadamente; fila vetorial com um descritor e um vetor. São3+4+2+1+1=11blocos. As ligações entre eles são empréstimos, não novas alocações.

Destruição possível: fila(descritor+vetor), nós de adjacência, missões e por último postos. Assim os empréstimos para missões/postos deixam de ser usados antes de seus proprietários serem liberados. Se uma implementação guardar postos ou missões em vetores embutidos, esses objetos não recebem free individual: esta tabela é um modelo explícito do exercício, não uma inferência sobre qualquer implementação. A campanha executável deste complemento usa pedidos embutidos, como documentado em E11/E12.

L3-C15-E07

Depuração#

Uma função retira definitivamente a missão da fila, tenta salvar o estado, recebe falha de escrita e informa sucesso. Identifique a inconsistência observável e proponha regra de falha que não anuncie persistência inexistente.

Ver uma dica

Uma falha de persistência não pode virar anúncio de conclusão durável.

Ver resolução comentada

O defeito combina retirada irreversível da fila, falha de escrita e mensagem de sucesso. Regra escolhida: consultar a cabeça sem retirá-la, preparar o novo estado, tentar salvar e verificar abertura/escritas/fechamento; em falha, manter missão pendente e comando enfileirado, informando que não foi persistido. Só confirmar o processamento após sucesso conforme o contrato da operação. Isso não promete transação resistente a falha de energia sem um protocolo de recuperação adicional.

L3-C15-E08

Depuração#

O relatório de vitória afirma que todos os postos estão acessíveis, mas o mapa inclui E isolado e o teste visitou apenas A,B,C,D. Corrija o critério de conclusão da campanha e a mensagem, sem apagar E para satisfazer o teste.

Ver uma dica

O conjunto de vértices preservado é parte do resultado, inclusive o que não foi alcançado.

Ver resolução comentada

Não anuncie “todos os postos acessíveis”. Mensagem correta: “A,B,C,D alcançados no estado atual; E permanece isolado e registrado”. O critério de conclusão deve indicar quais missões e rotas foram efetivamente cumpridas e manter E e pedidos sem caminho como pendências. A campanha pode terminar parcialmente, como “feitos1, pendentes1; isolados preservados”, sem apagar o vértice para fazer um teste passar.

L3-C15-E09

Implementação#

Fora do RPG: monte uma aplicação mínima de solicitações entre setores com quatro vértices, fila e consulta de alcance. Implemente criar, processar e listar solicitações, com teste de destino não alcançado.

Ver uma dica

Mantenha o pedido em um registro mesmo quando o comando não pode ser concluído.

Ver resolução comentada

A aplicação mínima tem quatro setores A,B,C,D e ligações AB,BC, com D isolado. A fila circular guarda índices dos pedidos por valor; criar, processar e listar são funções completas. Processar consulta a cabeça e usa BFS com fila para verificar alcance atual. Se não houver caminho, preserva a pendência e a cabeça da fila: é a política FIFO explícita deste ensaio. O teste primeiro processa coleção vazia, cria P1paraC e P2paraD, concluiP1 e recusaP2 sem perder seus dados. Os vetores são embutidos, sem alocação dinâmica a liberar.

main.c

#include <stdio.h>
typedef struct{int destino;int feita;} Solicitacao;
typedef struct{int mapa[4][4];Solicitacao pedidos[8];int usados;int fila[8];int inicio;int tamanho;} Aplicacao;
int alcancavel(const Aplicacao *a,int destino){if(destino<0||destino>=4)return 0;int visto[4]={0},fila[4],inicio=0,fim=0;visto[0]=1;fila[fim++]=0;while(inicio<fim){int u=fila[inicio++];if(u==destino)return 1;for(int v=0;v<4;v++)if(a->mapa[u][v] && !visto[v]){visto[v]=1;fila[fim++]=v;}}return 0;}
int criar(Aplicacao *a,int destino){if(destino<0||destino>=4||a->usados==8||a->tamanho==8)return 0;int id=a->usados;a->pedidos[id]=(Solicitacao){destino,0};a->fila[(a->inicio+a->tamanho)%8]=id;a->tamanho++;a->usados++;printf("Criada P%d para%c\n",id+1,'A'+destino);return 1;}
void processar(Aplicacao *a){if(a->tamanho==0){printf("Fila vazia\n");return;}int id=a->fila[a->inicio];Solicitacao *p=&a->pedidos[id];if(!alcancavel(a,p->destino)){printf("Recusa P%d: sem alcance; pendente preservada\n",id+1);return;}p->feita=1;a->inicio=(a->inicio+1)%8;a->tamanho--;printf("Processada P%d\n",id+1);}
void listar(const Aplicacao *a){for(int i=0;i<a->usados;i++)printf("P%d destino%c %s\n",i+1,'A'+a->pedidos[i].destino,a->pedidos[i].feita?"feita":"pendente");printf("Comandos pendentes:%d\n",a->tamanho);}
int main(void){Aplicacao a={.mapa={{0}},.pedidos={{0}},.usados=0,.fila={0},.inicio=0,.tamanho=0};a.mapa[0][1]=a.mapa[1][0]=1;a.mapa[1][2]=a.mapa[2][1]=1;processar(&a);if(!criar(&a,2)||!criar(&a,3))return 1;listar(&a);processar(&a);processar(&a);listar(&a);return 0;}
Editar e executar esta solução
Exemplo 1 · entrada e saída esperada

Entrada padrão

(sem entrada)

Saída esperada

Fila vazia
Criada P1 paraC
Criada P2 paraD
P1 destinoC pendente
P2 destinoD pendente
Comandos pendentes:2
Processada P1
Recusa P2: sem alcance; pendente preservada
P1 destinoC feita
P2 destinoD pendente
Comandos pendentes:1

Estado de saída: 0.

Editar e testar o exemplo 1

L3-C15-E10

Implementação#

Escreva um roteiro determinístico de aceitação do RPG: cadastrar posto, confirmar ligação, consultar caminho, solicitar viagem, bloquear ligação, recusar comando e encerrar. Registre saídas esperadas observáveis e verifique que os dados não são perdidos na recusa.

Ver uma dica

Verifique a recusa pelo estado exibido, e não apenas por uma mensagem genérica.

Ver resolução comentada

O roteiro determinístico completo acompanha o caso de entrada e os fontes. Cadastra A,B,C,D,E; confirma AB,AC,BD,CD; consulta D, obtendo A–B–D; cria P1paraD; bloqueia BD; processa e recusa P1, conservando seu plano e comando. Nova consulta encontra A–C–D; o plano antigo de P1 ainda aparece intacto. Replanejamento explícito atualiza P1 e permite executar. Depois cria P2paraEisolado, recusa por falta de plano, lista a fila contendo2 e encerra com uma missão feita e uma pendente.

As linhas observáveis essenciais são Recusa P1: B-D indisponivel; comando mantido., a consulta de P1 ainda pendente com o plano antigo, Executado P1: A C D após replanejar e Fila: 2 no encerramento parcial. O caso guarda stdout completo para comparar todos esses resultados, não só a palavra vitória.

bfs.c

#include "bfs.h"

static void publicar(BfsResultado *destino, const BfsResultado *origem)
{
    destino->vertices = origem->vertices;
    destino->origem = origem->origem;
    destino->quantidade = origem->quantidade;
    destino->inicializados = origem->inicializados;
    destino->listas = origem->listas;
    destino->entradas = origem->entradas;
    for (int i = 0; i < origem->vertices; i++) {
        destino->dist[i] = origem->dist[i];
        destino->pred[i] = origem->pred[i];
    }
    for (int i = 0; i < origem->quantidade; i++) {
        destino->ordem[i] = origem->ordem[i];
    }
}

int bfs_executar(const GrafoLista *g, int origem, BfsResultado *saida)
{
    BfsResultado temp;
    int fila[GR_CAP];
    int inicio = 0, fim = 0;
    if (g == NULL || saida == NULL || g->vertices < 0 || g->vertices > GR_CAP ||
        (g->dirigido != 0 && g->dirigido != 1) ||
        origem < 0 || origem >= g->vertices) {
        return BFS_INVALIDO;
    }
    temp.vertices = g->vertices;
    temp.origem = origem;
    temp.quantidade = 0;
    temp.inicializados = 0;
    temp.listas = 0;
    temp.entradas = 0;
    for (int v = 0; v < g->vertices; v++) {
        temp.dist[v] = -1;
        temp.pred[v] = -1;
        temp.inicializados++;
    }
    temp.dist[origem] = 0;
    temp.ordem[0] = origem;
    fila[fim++] = origem;
    temp.quantidade = fim;
    while (inicio < fim) {
        int u = fila[inicio++];
        const GrafoArco *p = gl_vizinhos(g, u);
        temp.listas++;
        while (p != NULL) {
            int v = p->destino;
            temp.entradas++;
            if (v < 0 || v >= g->vertices || p->estado < 1 || p->estado > 2) {
                return BFS_INVALIDO;
            }
            if (p->estado == GR_ABERTA && temp.dist[v] == -1) {
                if (fim >= g->vertices || fim >= GR_CAP) {
                    return BFS_LIMITE;
                }
                temp.dist[v] = temp.dist[u] + 1;
                temp.pred[v] = u;
                fila[fim] = v;
                temp.ordem[fim] = v;
                fim++;
                temp.quantidade = fim;
            }
            p = p->prox;
        }
    }
    publicar(saida, &temp);
    return BFS_OK;
}

int bfs_caminho(const BfsResultado *r, int destino, int *caminho,
                int capacidade, int *tamanho)
{
    int reverso[GR_CAP];
    int n = 0, v;
    if (r == NULL || caminho == NULL || tamanho == NULL ||
        r->vertices < 1 || r->vertices > GR_CAP ||
        r->origem < 0 || r->origem >= r->vertices ||
        r->quantidade < 1 || r->quantidade > r->vertices ||
        destino < 0 || destino >= r->vertices ||
        capacidade < 1 || capacidade > GR_CAP) {
        return BFS_INVALIDO;
    }
    if (r->dist[destino] == -1) {
        return BFS_SEM_CAMINHO;
    }
    if (r->dist[destino] < 0 || r->dist[destino] >= r->vertices) {
        return BFS_INVALIDO;
    }
    v = destino;
    for (;;) {
        int pai;
        if (n >= r->vertices || v < 0 || v >= r->vertices) {
            return BFS_INVALIDO;
        }
        reverso[n++] = v;
        if (v == r->origem) {
            if (r->dist[v] != 0 || r->pred[v] != -1) {
                return BFS_INVALIDO;
            }
            break;
        }
        if (r->dist[v] <= 0) {
            return BFS_INVALIDO;
        }
        pai = r->pred[v];
        if (pai < 0 || pai >= r->vertices || r->dist[pai] != r->dist[v] - 1) {
            return BFS_INVALIDO;
        }
        v = pai;
    }
    if (n > capacidade) {
        return BFS_LIMITE;
    }
    for (int i = 0; i < n; i++) {
        caminho[i] = reverso[n - 1 - i];
    }
    *tamanho = n;
    return BFS_OK;
}

bfs.h

#ifndef BFS_H
#define BFS_H
#include "grafos.h"
#include <stddef.h>

#define BFS_OK 1
#define BFS_SEM_CAMINHO 0
#define BFS_INVALIDO (-1)
#define BFS_LIMITE (-2)

typedef struct {
    int vertices;
    int origem;
    int quantidade;
    int dist[GR_CAP];
    int pred[GR_CAP];
    int ordem[GR_CAP];
    size_t inicializados;
    size_t listas;
    size_t entradas;
} BfsResultado;

int bfs_executar(const GrafoLista *g, int origem, BfsResultado *saida);
int bfs_caminho(const BfsResultado *r, int destino, int *caminho,
                int capacidade, int *tamanho);
#endif

campanha_demo.c

#include "grafos.h"
#include "bfs.h"
#include "fila.h"
#include "hash.h"
#include <stdio.h>

#define PEDIDOS_MAX 8

typedef struct {
    int id, destino, status, comando;
    int quantidade, rota[GR_CAP];
} Solicitacao;

typedef struct {
    GrafoLista mapa;
    HashTabela itens;
    Fila *comandos;
    int cadastrado[GR_CAP];
    Solicitacao pedidos[PEDIDOS_MAX];
    int usados;
} Campanha;

static void destruir(Campanha *c)
{
    fila_destruir(&c->comandos);
    gl_destruir(&c->mapa);
    hash_destruir(&c->itens);
}

static int iniciar(Campanha *c)
{
    HashRegistro marca = {0, "Marca", 1};
    size_t comparacoes;
    c->comandos = NULL;
    c->usados = 0;
    for (int i = 0; i < GR_CAP; i++) {
        c->cadastrado[i] = 0;
    }
    (void)gl_iniciar(&c->mapa, GR_CAP, 0);
    hash_iniciar(&c->itens);
    if (fila_criar(&c->comandos, 4) != FILA_OK ||
        hash_inserir(&c->itens, marca, &comparacoes) != HASH_OK) {
        destruir(c);
        return 0;
    }
    return 1;
}

static int posto(const Campanha *c, int v)
{
    return v >= 0 && v < GR_CAP && c->cadastrado[v];
}

static int planejar(const Campanha *c, int destino, int *rota, int *n)
{
    BfsResultado resultado;
    if (!posto(c, 0) || !posto(c, destino) ||
        bfs_executar(&c->mapa, 0, &resultado) != BFS_OK) {
        return BFS_INVALIDO;
    }
    return bfs_caminho(&resultado, destino, rota, GR_CAP, n);
}

static void imprimir_rota(const int *rota, int n)
{
    if (n == 0) {
        printf(" sem-plano");
    }
    for (int i = 0; i < n; i++) {
        printf(" %c", 'A' + rota[i]);
    }
}

static Solicitacao *pedido(Campanha *c, int id)
{
    if (id < 1 || id > c->usados) {
        return NULL;
    }
    return &c->pedidos[id - 1];
}

static void consultar(Campanha *c, int destino)
{
    int rota[GR_CAP], n = 0;
    int codigo = planejar(c, destino, rota, &n);
    if (codigo == BFS_OK) {
        printf("Consulta:");
        imprimir_rota(rota, n);
        printf("; arestas=%d.\n", n - 1);
    } else if (codigo == BFS_SEM_CAMINHO) {
        puts("Consulta: destino nao alcancado.");
    } else {
        puts("Consulta recusada: cadastro invalido.");
    }
}

static void mostrar_pedido(const Solicitacao *p)
{
    printf("P%d A->%c status=%s comando=%d plano:", p->id, 'A' + p->destino,
           p->status == 1 ? "pendente" : "feito", p->comando);
    imprimir_rota(p->rota, p->quantidade);
    putchar('\n');
}

static void criar_pedido(Campanha *c, int destino)
{
    Solicitacao novo = {0};
    int codigo;
    if (c->usados == PEDIDOS_MAX || !posto(c, 0) || !posto(c, destino)) {
        puts("Pedido recusado: cadastro ou limite.");
        return;
    }
    novo.id = c->usados + 1;
    novo.destino = destino;
    novo.status = novo.comando = 1;
    codigo = planejar(c, destino, novo.rota, &novo.quantidade);
    if (codigo != BFS_OK && codigo != BFS_SEM_CAMINHO) {
        puts("Pedido recusado: falha no plano.");
        return;
    }
    codigo = fila_entrar(c->comandos, novo.id);
    if (codigo != FILA_OK) {
        printf("Pedido recusado: fila codigo=%d.\n", codigo);
        return;
    }
    c->pedidos[c->usados] = novo;
    c->usados++;
    mostrar_pedido(&novo);
}

static void replanejar(Campanha *c, int id)
{
    Solicitacao *p = pedido(c, id);
    int rota[GR_CAP], n = 0;
    if (p == NULL || p->status != 1 ||
        planejar(c, p->destino, rota, &n) != BFS_OK) {
        puts("Replanejamento recusado; plano anterior conservado.");
        return;
    }
    for (int i = 0; i < n; i++) {
        p->rota[i] = rota[i];
    }
    p->quantidade = n;
    printf("Replanejado P%d:", id);
    imprimir_rota(p->rota, n);
    putchar('\n');
}

static void processar(Campanha *c)
{
    int id, retirado;
    Solicitacao *p;
    if (fila_consultar(c->comandos, 0, &id) != FILA_OK) {
        puts("Fila vazia; nada processado.");
        return;
    }
    p = pedido(c, id);
    if (p == NULL || p->status != 1 || p->comando != 1) {
        puts("Estado incoerente; comando conservado.");
        return;
    }
    if (p->quantidade < 1) {
        printf("Recusa P%d: sem plano; comando mantido.\n", id);
        return;
    }
    if (p->quantidade > GR_CAP || p->rota[0] != 0 ||
        p->rota[p->quantidade - 1] != p->destino) {
        puts("Plano incoerente; comando conservado.");
        return;
    }
    for (int i = 0; i < p->quantidade; i++) {
        if (!posto(c, p->rota[i])) {
            printf("Recusa P%d: cadastro do plano; comando mantido.\n", id);
            return;
        }
    }
    for (int i = 1; i < p->quantidade; i++) {
        int u = p->rota[i - 1], v = p->rota[i];
        if (gl_estado(&c->mapa, u, v) != GR_ABERTA) {
            printf("Recusa P%d: %c-%c indisponivel; comando mantido.\n",
                   id, 'A' + u, 'A' + v);
            return;
        }
    }
    if (fila_sair(c->comandos, &retirado) != FILA_OK) {
        puts("Falha interna de fila.");
        return;
    }
    p->status = 2;
    p->comando = 0;
    printf("Executado P%d:", retirado);
    imprimir_rota(p->rota, p->quantidade);
    putchar('\n');
}

static void listar(const Campanha *c)
{
    printf("Postos:");
    for (int v = 0; v < GR_CAP; v++) {
        if (c->cadastrado[v]) {
            printf(" %c", 'A' + v);
        }
    }
    printf("\nFila:");
    for (size_t i = 0; i < fila_tamanho(c->comandos); i++) {
        int id;
        if (fila_consultar(c->comandos, (int)i, &id) == FILA_OK) {
            printf(" %d", id);
        }
    }
    putchar('\n');
    for (int i = 0; i < c->usados; i++) {
        mostrar_pedido(&c->pedidos[i]);
    }
}

static void resumir(const Campanha *c)
{
    int feitos = 0;
    for (int i = 0; i < c->usados; i++) {
        feitos += c->pedidos[i].status == 2;
    }
    printf("Encerramento parcial: feitos=%d pendentes=%d; isolados preservados.\n",
           feitos, c->usados - feitos);
}

static int ler(int valores[3])
{
    char linha[80];
    size_t n = 0, i = 0;
    int ch, ruim = 0, partes = 0;
    const int aridade[13] = {1,2,3,2,2,2,1,2,3,1,2,3,3};
    while ((ch = fgetc(stdin)) != EOF && ch != '\n') {
        if (ch < 32 || ch > 126 || n >= sizeof linha - 1) {
            ruim = 1;
        } else {
            linha[n++] = (char)ch;
        }
    }
    if (ch == EOF && ferror(stdin)) {
        return -2;
    }
    if (ch == EOF && n == 0 && !ruim) {
        return 0;
    }
    if (ch == EOF || ruim) {
        return -1;
    }
    linha[n] = '\0';
    while (i < n) {
        int valor = 0, digitos = 0;
        while (i < n && linha[i] == ' ') {
            i++;
        }
        if (i == n) {
            break;
        }
        if (partes == 3) {
            return -1;
        }
        while (i < n && linha[i] >= '0' && linha[i] <= '9') {
            if (digitos == 2) {
                return -1;
            }
            valor = valor * 10 + (linha[i] - '0');
            digitos++;
            i++;
        }
        if (digitos == 0 || (i < n && linha[i] != ' ')) {
            return -1;
        }
        valores[partes++] = valor;
    }
    if (partes == 0 || valores[0] > 12 || partes != aridade[valores[0]]) {
        return -1;
    }
    return 1;
}

int main(void)
{
    Campanha c;
    int valores[3], status = 0;
    if (!iniciar(&c)) {
        puts("Montagem recusada; recursos obtidos foram liberados.");
        return 1;
    }
    puts("Campanha pronta: simulacao, 8 slots, 8 pedidos, fila 4.");
    for (;;) {
        int leitura = ler(valores);
        int op, a = 0, b = 0;
        if (leitura == -2) {
            puts("Falha de leitura; encerrar sem executar linha.");
            status = 1;
            break;
        }
        if (leitura == 0) {
            puts("EOF: encerrar.");
            break;
        }
        if (leitura < 0) {
            puts("Entrada invalida; estado preservado.");
            continue;
        }
        op = valores[0];
        if (op == 0) {
            puts("Saida voluntaria.");
            break;
        }
        if (op == 1 || op == 3 || op == 4 || op == 5 || op == 7 || op == 10) {
            a = valores[1];
        } else if (op == 2 || op == 8 || op == 11 || op == 12) {
            a = valores[1];
            b = valores[2];
        }
        switch (op) {
        case 1:
            if (a >= GR_CAP || c.cadastrado[a]) {
                puts("Cadastro recusado.");
            } else {
                c.cadastrado[a] = 1;
                printf("Posto %c cadastrado.\n", 'A' + a);
            }
            break;
        case 2:
        case 8:
        case 12:
            if (!posto(&c, a) || !posto(&c, b)) {
                puts("Rota recusada: cadastro invalido.");
            } else {
                int codigo = op == 2 ? gl_adicionar(&c.mapa, a, b, 1) :
                    gl_disponivel(&c.mapa, a, b, op == 12);
                printf("Rota %c-%c op=%d codigo=%d.\n", 'A' + a, 'A' + b,
                       op, codigo);
            }
            break;
        case 3:
            consultar(&c, a);
            break;
        case 4:
            criar_pedido(&c, a);
            break;
        case 5: {
            const Solicitacao *p = pedido(&c, a);
            if (p == NULL) {
                puts("Pedido ausente.");
            } else {
                mostrar_pedido(p);
            }
            break;
        }
        case 6:
            processar(&c);
            break;
        case 7:
            replanejar(&c, a);
            break;
        case 9:
            listar(&c);
            break;
        case 10: {
            HashRegistro item;
            size_t comparacoes;
            if (hash_buscar(&c.itens, a, &item, &comparacoes) == HASH_OK) {
                printf("Item %d %s quantidade=%d.\n", item.chave,
                       item.nome, item.quantidade);
            } else {
                puts("Item ausente.");
            }
            break;
        }
        case 11: {
            HashRegistro item = {0, "Item", 0};
            size_t comparacoes;
            item.chave = a;
            item.quantidade = b;
            printf("Item inserir codigo=%d.\n",
                   hash_inserir(&c.itens, item, &comparacoes));
            break;
        }
        }
    }
    resumir(&c);
    destruir(&c);
    puts("Sessao encerrada; donos liberados.");
    return status;
}

fila.c

#include "fila.h"
#include <stdint.h>
#include <stdlib.h>

struct Fila {
    int *dados;
    size_t inicio;
    size_t tamanho;
    size_t capacidade;
};

int fila_criar(Fila **dona, size_t capacidade)
{
    Fila *nova;
    if (dona == NULL || *dona != NULL || capacidade == 0 ||
        capacidade > 32 || capacidade > SIZE_MAX / sizeof(int)) {
        return FILA_INVALIDO;
    }
    nova = malloc(sizeof *nova);
    if (nova == NULL) {
        return FILA_MEMORIA;
    }
    nova->dados = NULL;
    nova->inicio = 0;
    nova->tamanho = 0;
    nova->capacidade = capacidade;
    nova->dados = malloc(capacidade * sizeof *nova->dados);
    if (nova->dados == NULL) {
        free(nova);
        return FILA_MEMORIA;
    }
    *dona = nova;
    return FILA_OK;
}

int fila_entrar(Fila *f, int valor)
{
    size_t posicao;
    if (f == NULL) {
        return FILA_INVALIDO;
    }
    if (f->tamanho == f->capacidade) {
        return FILA_CHEIA;
    }
    posicao = (f->inicio + f->tamanho) % f->capacidade;
    f->dados[posicao] = valor;
    f->tamanho++;
    return FILA_OK;
}

int fila_sair(Fila *f, int *saida)
{
    int valor;
    if (f == NULL || saida == NULL) {
        return FILA_INVALIDO;
    }
    if (f->tamanho == 0) {
        return FILA_VAZIA;
    }
    valor = f->dados[f->inicio];
    f->inicio = (f->inicio + 1) % f->capacidade;
    f->tamanho--;
    *saida = valor;
    return FILA_OK;
}

int fila_consultar(const Fila *f, int posicao, int *saida)
{
    size_t i;
    if (f == NULL || saida == NULL) {
        return FILA_INVALIDO;
    }
    if (posicao < 0) {
        return FILA_POSICAO;
    }
    i = (size_t)posicao;
    if (i >= f->tamanho) {
        return FILA_POSICAO;
    }
    *saida = f->dados[(f->inicio + i) % f->capacidade];
    return FILA_OK;
}

size_t fila_inicio(const Fila *f)
{
    return f->inicio;
}

size_t fila_tamanho(const Fila *f)
{
    return f->tamanho;
}

size_t fila_capacidade(const Fila *f)
{
    return f->capacidade;
}

void fila_destruir(Fila **dona)
{
    if (dona == NULL || *dona == NULL) {
        return;
    }
    free((*dona)->dados);
    free(*dona);
    *dona = NULL;
}

fila.h

#ifndef FILA_H
#define FILA_H
#include <stddef.h>

#define FILA_OK 1
#define FILA_VAZIA 0
#define FILA_INVALIDO (-1)
#define FILA_CHEIA (-2)
#define FILA_MEMORIA (-3)
#define FILA_POSICAO (-4)

typedef struct Fila Fila;

int fila_criar(Fila **dona, size_t capacidade);
int fila_entrar(Fila *f, int valor);
int fila_sair(Fila *f, int *saida);
int fila_consultar(const Fila *f, int posicao, int *saida);
size_t fila_inicio(const Fila *f);
size_t fila_tamanho(const Fila *f);
size_t fila_capacidade(const Fila *f);
void fila_destruir(Fila **dona);
#endif

grafos.c

#include "grafos.h"
#include <stddef.h>
#include <stdlib.h>

static int configuracao(int n, int dirigido)
{
    return n >= 0 && n <= GR_CAP && (dirigido == 0 || dirigido == 1);
}

static int indice(int n, int v)
{
    return v >= 0 && v < n;
}

static int forma_m(const GrafoMatriz *g)
{
    return g != NULL && configuracao(g->vertices, g->dirigido);
}

static int forma_l(const GrafoLista *g)
{
    return g != NULL && configuracao(g->vertices, g->dirigido);
}

int gm_iniciar(GrafoMatriz *g, int n, int dirigido)
{
    if (g == NULL || !configuracao(n, dirigido)) {
        return GR_INVALIDO;
    }
    for (int u = 0; u < GR_CAP; u++) {
        for (int v = 0; v < GR_CAP; v++) {
            g->aresta[u][v] = 0;
        }
    }
    g->vertices = n;
    g->dirigido = dirigido;
    return GR_OK;
}

int gm_estado(const GrafoMatriz *g, int u, int v)
{
    if (!forma_m(g) || !indice(g->vertices, u) || !indice(g->vertices, v)) {
        return GR_INVALIDO;
    }
    return g->aresta[u][v];
}

int gm_adicionar(GrafoMatriz *g, int u, int v, int disponivel)
{
    if (gm_estado(g, u, v) < 0 || u == v ||
        (disponivel != 0 && disponivel != 1)) {
        return GR_INVALIDO;
    }
    if (g->aresta[u][v] != 0) {
        return GR_DUPLICADA;
    }
    g->aresta[u][v] = disponivel ? GR_ABERTA : GR_FECHADA;
    if (!g->dirigido) {
        g->aresta[v][u] = g->aresta[u][v];
    }
    return GR_OK;
}

int gm_remover(GrafoMatriz *g, int u, int v)
{
    int estado = gm_estado(g, u, v);
    if (estado < 0 || u == v) {
        return GR_INVALIDO;
    }
    if (estado == 0) {
        return GR_AUSENTE;
    }
    g->aresta[u][v] = 0;
    if (!g->dirigido) {
        g->aresta[v][u] = 0;
    }
    return GR_OK;
}

int gm_disponivel(GrafoMatriz *g, int u, int v, int disponivel)
{
    int estado = gm_estado(g, u, v);
    if (estado < 0 || (disponivel != 0 && disponivel != 1)) {
        return GR_INVALIDO;
    }
    if (estado == 0) {
        return GR_AUSENTE;
    }
    g->aresta[u][v] = disponivel ? GR_ABERTA : GR_FECHADA;
    if (!g->dirigido) {
        g->aresta[v][u] = g->aresta[u][v];
    }
    return GR_OK;
}

int gm_conferir(const GrafoMatriz *g)
{
    if (!forma_m(g)) {
        return 0;
    }
    for (int u = 0; u < GR_CAP; u++) {
        for (int v = 0; v < GR_CAP; v++) {
            int e = g->aresta[u][v];
            if (e < 0 || e > 2 || (u == v && e != 0) ||
                ((u >= g->vertices || v >= g->vertices) && e != 0) ||
                (!g->dirigido && e != g->aresta[v][u])) {
                return 0;
            }
        }
    }
    return 1;
}

int gl_iniciar(GrafoLista *g, int n, int dirigido)
{
    if (g == NULL || !configuracao(n, dirigido)) {
        return GR_INVALIDO;
    }
    for (int u = 0; u < GR_CAP; u++) {
        g->cabeca[u] = NULL;
    }
    g->vertices = n;
    g->dirigido = dirigido;
    return GR_OK;
}

static GrafoArco **posicao(GrafoLista *g, int u, int v)
{
    GrafoArco **p = &g->cabeca[u];
    while (*p != NULL && (*p)->destino < v) {
        p = &(*p)->prox;
    }
    return p;
}

const GrafoArco *gl_vizinhos(const GrafoLista *g, int u)
{
    if (!forma_l(g) || !indice(g->vertices, u)) {
        return NULL;
    }
    return g->cabeca[u];
}

int gl_estado(const GrafoLista *g, int u, int v)
{
    const GrafoArco *p;
    if (!forma_l(g) || !indice(g->vertices, u) || !indice(g->vertices, v)) {
        return GR_INVALIDO;
    }
    p = g->cabeca[u];
    while (p != NULL && p->destino < v) {
        p = p->prox;
    }
    return p != NULL && p->destino == v ? p->estado : GR_AUSENTE;
}

int gl_adicionar(GrafoLista *g, int u, int v, int disponivel)
{
    GrafoArco **pu, **pv = NULL;
    GrafoArco *a, *b = NULL;
    int estado;
    if (gl_estado(g, u, v) < 0 || u == v ||
        (disponivel != 0 && disponivel != 1)) {
        return GR_INVALIDO;
    }
    pu = posicao(g, u, v);
    if (*pu != NULL && (*pu)->destino == v) {
        return GR_DUPLICADA;
    }
    if (!g->dirigido) {
        pv = posicao(g, v, u);
        if (*pv != NULL && (*pv)->destino == u) {
            return GR_INVALIDO;
        }
    }
    a = malloc(sizeof *a);
    if (a == NULL) {
        return GR_MEMORIA;
    }
    if (!g->dirigido) {
        b = malloc(sizeof *b);
        if (b == NULL) {
            free(a);
            return GR_MEMORIA;
        }
    }
    estado = disponivel ? GR_ABERTA : GR_FECHADA;
    a->destino = v;
    a->estado = estado;
    a->prox = *pu;
    if (b != NULL) {
        b->destino = u;
        b->estado = estado;
        b->prox = *pv;
    }
    *pu = a;
    if (b != NULL) {
        *pv = b;
    }
    return GR_OK;
}

int gl_remover(GrafoLista *g, int u, int v)
{
    GrafoArco **pu, **pv = NULL;
    GrafoArco *a, *b = NULL;
    int estado = gl_estado(g, u, v);
    if (estado < 0 || u == v) {
        return GR_INVALIDO;
    }
    if (estado == 0) {
        return GR_AUSENTE;
    }
    pu = posicao(g, u, v);
    if (!g->dirigido) {
        pv = posicao(g, v, u);
        if (*pv == NULL || (*pv)->destino != u) {
            return GR_INVALIDO;
        }
        b = *pv;
    }
    a = *pu;
    *pu = a->prox;
    if (b != NULL) {
        *pv = b->prox;
    }
    free(a);
    if (b != NULL) {
        free(b);
    }
    return GR_OK;
}

int gl_disponivel(GrafoLista *g, int u, int v, int disponivel)
{
    GrafoArco **pu, **pv = NULL;
    int estado = gl_estado(g, u, v);
    if (estado < 0 || (disponivel != 0 && disponivel != 1)) {
        return GR_INVALIDO;
    }
    if (estado == 0) {
        return GR_AUSENTE;
    }
    pu = posicao(g, u, v);
    if (!g->dirigido) {
        pv = posicao(g, v, u);
        if (*pv == NULL || (*pv)->destino != u) {
            return GR_INVALIDO;
        }
    }
    (*pu)->estado = disponivel ? GR_ABERTA : GR_FECHADA;
    if (pv != NULL) {
        (*pv)->estado = (*pu)->estado;
    }
    return GR_OK;
}

int gl_grau(const GrafoLista *g, int u)
{
    const GrafoArco *p;
    int grau = 0;
    if (!forma_l(g) || !indice(g->vertices, u)) {
        return GR_INVALIDO;
    }
    p = g->cabeca[u];
    while (p != NULL) {
        grau++;
        p = p->prox;
    }
    return grau;
}

int gl_conferir(const GrafoLista *g)
{
    int visto[GR_CAP][GR_CAP] = {{0}};
    int total = 0;
    if (!forma_l(g)) {
        return 0;
    }
    for (int u = 0; u < GR_CAP; u++) {
        const GrafoArco *p = g->cabeca[u];
        int anterior = -1;
        if (u >= g->vertices && p != NULL) {
            return 0;
        }
        while (p != NULL) {
            if (total >= GR_CAP * (GR_CAP - 1) ||
                !indice(g->vertices, p->destino) || p->destino == u ||
                p->destino <= anterior || p->estado < 1 || p->estado > 2) {
                return 0;
            }
            visto[u][p->destino] = p->estado;
            anterior = p->destino;
            total++;
            p = p->prox;
        }
    }
    if (!g->dirigido) {
        for (int u = 0; u < g->vertices; u++) {
            for (int v = 0; v < g->vertices; v++) {
                if (visto[u][v] != visto[v][u]) {
                    return 0;
                }
            }
        }
    }
    return 1;
}

void gl_destruir(GrafoLista *g)
{
    if (g == NULL) {
        return;
    }
    for (int u = 0; u < GR_CAP; u++) {
        while (g->cabeca[u] != NULL) {
            GrafoArco *p = g->cabeca[u];
            g->cabeca[u] = p->prox;
            free(p);
        }
    }
    g->vertices = 0;
    g->dirigido = 0;
}

int gl_converter(const GrafoMatriz *origem, GrafoLista *destino)
{
    GrafoLista temporario;
    if (!gm_conferir(origem) || !forma_l(destino)) {
        return GR_INVALIDO;
    }
    (void)gl_iniciar(&temporario, origem->vertices, origem->dirigido);
    for (int u = 0; u < origem->vertices; u++) {
        for (int v = 0; v < origem->vertices; v++) {
            int estado = origem->aresta[u][v];
            if (estado != 0 && (origem->dirigido || u < v)) {
                int r = gl_adicionar(&temporario, u, v, estado == GR_ABERTA);
                if (r != GR_OK) {
                    gl_destruir(&temporario);
                    return r;
                }
            }
        }
    }
    gl_destruir(destino);
    *destino = temporario;
    (void)gl_iniciar(&temporario, 0, 0);
    return GR_OK;
}

grafos.h

#ifndef GRAFOS_H
#define GRAFOS_H

#define GR_CAP 8
#define GR_OK 1
#define GR_AUSENTE 0
#define GR_INVALIDO (-1)
#define GR_DUPLICADA (-2)
#define GR_MEMORIA (-3)
#define GR_FECHADA 1
#define GR_ABERTA 2

typedef struct {
    int vertices;
    int dirigido;
    int aresta[GR_CAP][GR_CAP];
} GrafoMatriz;

typedef struct GrafoArco {
    int destino;
    int estado;
    struct GrafoArco *prox;
} GrafoArco;

typedef struct {
    int vertices;
    int dirigido;
    GrafoArco *cabeca[GR_CAP];
} GrafoLista;

int gm_iniciar(GrafoMatriz *g, int vertices, int dirigido);
int gm_estado(const GrafoMatriz *g, int u, int v);
int gm_adicionar(GrafoMatriz *g, int u, int v, int disponivel);
int gm_remover(GrafoMatriz *g, int u, int v);
int gm_disponivel(GrafoMatriz *g, int u, int v, int disponivel);
int gm_conferir(const GrafoMatriz *g);
int gl_iniciar(GrafoLista *g, int vertices, int dirigido);
int gl_estado(const GrafoLista *g, int u, int v);
int gl_adicionar(GrafoLista *g, int u, int v, int disponivel);
int gl_remover(GrafoLista *g, int u, int v);
int gl_disponivel(GrafoLista *g, int u, int v, int disponivel);
const GrafoArco *gl_vizinhos(const GrafoLista *g, int u);
int gl_grau(const GrafoLista *g, int u);
int gl_conferir(const GrafoLista *g);
int gl_converter(const GrafoMatriz *origem, GrafoLista *destino);
void gl_destruir(GrafoLista *g);
#endif

hash.c

#include "hash.h"
#include <stdio.h>
#include <stdlib.h>

struct HashNo {
    HashRegistro dado;
    struct HashNo *prox;
};

static int forma(const HashTabela *t)
{
    return t != NULL && t->tamanho <= HASH_MAX_NOS;
}

static int chave_valida(int chave)
{
    return chave >= 0 && chave <= 99;
}

static size_t indice(int chave)
{
    return (size_t)(chave % HASH_BUCKETS);
}

static int dado_valido(HashRegistro d)
{
    if (!chave_valida(d.chave) || d.quantidade < 0 || d.quantidade > 100) {
        return 0;
    }
    for (size_t i = 0; i < sizeof d.nome; i++) {
        if (d.nome[i] == '\0') {
            return i > 0;
        }
        if (d.nome[i] < ' ' || d.nome[i] > '~') {
            return 0;
        }
    }
    return 0;
}

void hash_iniciar(HashTabela *t)
{
    if (t == NULL) {
        return;
    }
    for (size_t i = 0; i < HASH_BUCKETS; i++) {
        t->buckets[i] = NULL;
    }
    t->tamanho = 0;
}

int hash_inserir(HashTabela *t, HashRegistro dado, size_t *comparacoes)
{
    HashNo **ligacao;
    HashNo *novo;
    if (!forma(t) || comparacoes == NULL || !dado_valido(dado)) {
        return HASH_INVALIDO;
    }
    *comparacoes = 0;
    ligacao = &t->buckets[indice(dado.chave)];
    while (*ligacao != NULL) {
        (*comparacoes)++;
        if ((*ligacao)->dado.chave == dado.chave) {
            return HASH_DUPLICADO;
        }
        ligacao = &(*ligacao)->prox;
    }
    if (t->tamanho == HASH_MAX_NOS) {
        return HASH_LIMITE;
    }
    novo = malloc(sizeof *novo);
    if (novo == NULL) {
        return HASH_MEMORIA;
    }
    novo->dado = dado;
    novo->prox = NULL;
    *ligacao = novo;
    t->tamanho++;
    return HASH_OK;
}

int hash_buscar(const HashTabela *t, int chave, HashRegistro *saida,
                size_t *comparacoes)
{
    const HashNo *p;
    if (!forma(t) || !chave_valida(chave) || saida == NULL ||
        comparacoes == NULL) {
        return HASH_INVALIDO;
    }
    *comparacoes = 0;
    p = t->buckets[indice(chave)];
    while (p != NULL) {
        (*comparacoes)++;
        if (p->dado.chave == chave) {
            *saida = p->dado;
            return HASH_OK;
        }
        p = p->prox;
    }
    return HASH_AUSENTE;
}

int hash_remover(HashTabela *t, int chave, HashRegistro *saida,
                 size_t *comparacoes)
{
    HashNo **ligacao;
    if (!forma(t) || !chave_valida(chave) || saida == NULL ||
        comparacoes == NULL) {
        return HASH_INVALIDO;
    }
    *comparacoes = 0;
    ligacao = &t->buckets[indice(chave)];
    while (*ligacao != NULL) {
        HashNo *p = *ligacao;
        (*comparacoes)++;
        if (p->dado.chave == chave) {
            HashRegistro original = p->dado;
            *ligacao = p->prox;
            free(p);
            t->tamanho--;
            *saida = original;
            return HASH_OK;
        }
        ligacao = &p->prox;
    }
    return HASH_AUSENTE;
}

int hash_conferir(const HashTabela *t)
{
    int vistos[100] = {0};
    size_t total = 0;
    if (!forma(t)) {
        return 0;
    }
    for (size_t i = 0; i < HASH_BUCKETS; i++) {
        const HashNo *p = t->buckets[i];
        while (p != NULL) {
            if (total >= HASH_MAX_NOS || !dado_valido(p->dado)) {
                return 0;
            }
            if (indice(p->dado.chave) != i || vistos[p->dado.chave]) {
                return 0;
            }
            vistos[p->dado.chave] = 1;
            total++;
            p = p->prox;
        }
    }
    return total == t->tamanho;
}

void hash_listar(const HashTabela *t)
{
    for (size_t i = 0; i < HASH_BUCKETS; i++) {
        const HashNo *p = t->buckets[i];
        printf("[%zu]", i);
        while (p != NULL) {
            printf(" %d:%s:%d", p->dado.chave, p->dado.nome,
                   p->dado.quantidade);
            p = p->prox;
        }
        putchar('\n');
    }
}

void hash_relatar(const HashTabela *t)
{
    size_t maior = 0;
    size_t vazios = 0;
    for (size_t i = 0; i < HASH_BUCKETS; i++) {
        size_t n = 0;
        const HashNo *p = t->buckets[i];
        while (p != NULL) {
            n++;
            p = p->prox;
        }
        if (n == 0) {
            vazios++;
        }
        if (n > maior) {
            maior = n;
        }
    }
    printf("n=%zu carga=%.1f maior=%zu vazios=%zu\n", t->tamanho,
           (double)t->tamanho / HASH_BUCKETS, maior, vazios);
}

void hash_destruir(HashTabela *t)
{
    if (t == NULL) {
        return;
    }
    for (size_t i = 0; i < HASH_BUCKETS; i++) {
        while (t->buckets[i] != NULL) {
            HashNo *p = t->buckets[i];
            t->buckets[i] = p->prox;
            free(p);
        }
    }
    t->tamanho = 0;
}

hash.h

#ifndef HASH_H
#define HASH_H
#include <stddef.h>

#define HASH_BUCKETS 5
#define HASH_MAX_NOS 16
#define HASH_OK 1
#define HASH_AUSENTE 0
#define HASH_INVALIDO (-1)
#define HASH_DUPLICADO (-2)
#define HASH_MEMORIA (-3)
#define HASH_LIMITE (-4)

typedef struct {
    int chave;
    char nome[16];
    int quantidade;
} HashRegistro;

typedef struct HashNo HashNo;
typedef struct {
    HashNo *buckets[HASH_BUCKETS];
    size_t tamanho;
} HashTabela;

void hash_iniciar(HashTabela *t);
int hash_inserir(HashTabela *t, HashRegistro dado, size_t *comparacoes);
int hash_buscar(const HashTabela *t, int chave, HashRegistro *saida,
                size_t *comparacoes);
int hash_remover(HashTabela *t, int chave, HashRegistro *saida,
                 size_t *comparacoes);
int hash_conferir(const HashTabela *t);
void hash_listar(const HashTabela *t);
void hash_relatar(const HashTabela *t);
void hash_destruir(HashTabela *t);
#endif
Editar e executar esta solução
Exemplo 1 · entrada e saída esperada

Entrada padrão

1 0
1 1
1 2
1 3
1 4
2 0 1
2 0 2
2 1 3
2 2 3
3 3
4 3
8 1 3
6
5 1
3 3
5 1
7 1
6
4 4
6
9
0

Saída esperada

Campanha pronta: simulacao, 8 slots, 8 pedidos, fila 4.
Posto A cadastrado.
Posto B cadastrado.
Posto C cadastrado.
Posto D cadastrado.
Posto E cadastrado.
Rota A-B op=2 codigo=1.
Rota A-C op=2 codigo=1.
Rota B-D op=2 codigo=1.
Rota C-D op=2 codigo=1.
Consulta: A B D; arestas=2.
P1 A->D status=pendente comando=1 plano: A B D
Rota B-D op=8 codigo=1.
Recusa P1: B-D indisponivel; comando mantido.
P1 A->D status=pendente comando=1 plano: A B D
Consulta: A C D; arestas=2.
P1 A->D status=pendente comando=1 plano: A B D
Replanejado P1: A C D
Executado P1: A C D
P2 A->E status=pendente comando=1 plano: sem-plano
Recusa P2: sem plano; comando mantido.
Postos: A B C D E
Fila: 2
P1 A->D status=feito comando=0 plano: A C D
P2 A->E status=pendente comando=1 plano: sem-plano
Saida voluntaria.
Encerramento parcial: feitos=1 pendentes=1; isolados preservados.
Sessao encerrada; donos liberados.

Estado de saída: 0.

Editar e testar o exemplo 1

L3-C15-E11

Implementação#

Prepare a demonstração final com build reproduzível, testes das estruturas utilizadas, verificação de alocações/liberações e documento de limites. Inclua ao menos uma falha de entrada e uma operação sobre coleção vazia.

Ver uma dica

Combine construção reproduzível, testes lógicos e verificação explícita da limpeza.

Ver resolução comentada

A demonstração usa todos os módulos C/H entregues e uma adaptação somente deste gabarito: após destruir a campanha, confere dono da fila nulo, tamanho do hash zero e todas as cabeças de hash/grafo nulas. Os demais arquivos são cópias da implementação da unidade.

cc -std=c17 -Wall -Wextra -Wpedantic -Werror campanha_demo.c grafos.c bfs.c fila.c hash.c -o campanha
./campanha

O caso principal cobre hash inicial, grafo, fila, BFS, recusa e replanejamento; o segundo começa com linha inválida x, operação na fila vazia e item ausente, depois encerra. A checagem final precisa imprimir1 em ambos. No roteiro principal são obtidos dois blocos da fila, um nó hash inicial e oito nós para quatro arestas não dirigidas: onze blocos, cada qual com caminho de liberação no destruidor de seu proprietário. Pedidos e rotas são embutidos e não recebem free.

Limites: oito slots de postos, oito pedidos, fila de quatro comandos, hash de cinco buckets/até16itens e parser de linhas limitado. As raízes nulas e a execução com sanitizadores investigam estes fluxos, sem afirmar prova universal de ausência de vazamento. Não há gravação de partidas nesta demonstração; a política de falha de persistência foi discutida em E07. O teste não anuncia persistência que o programa não realiza.

bfs.c

#include "bfs.h"

static void publicar(BfsResultado *destino, const BfsResultado *origem)
{
    destino->vertices = origem->vertices;
    destino->origem = origem->origem;
    destino->quantidade = origem->quantidade;
    destino->inicializados = origem->inicializados;
    destino->listas = origem->listas;
    destino->entradas = origem->entradas;
    for (int i = 0; i < origem->vertices; i++) {
        destino->dist[i] = origem->dist[i];
        destino->pred[i] = origem->pred[i];
    }
    for (int i = 0; i < origem->quantidade; i++) {
        destino->ordem[i] = origem->ordem[i];
    }
}

int bfs_executar(const GrafoLista *g, int origem, BfsResultado *saida)
{
    BfsResultado temp;
    int fila[GR_CAP];
    int inicio = 0, fim = 0;
    if (g == NULL || saida == NULL || g->vertices < 0 || g->vertices > GR_CAP ||
        (g->dirigido != 0 && g->dirigido != 1) ||
        origem < 0 || origem >= g->vertices) {
        return BFS_INVALIDO;
    }
    temp.vertices = g->vertices;
    temp.origem = origem;
    temp.quantidade = 0;
    temp.inicializados = 0;
    temp.listas = 0;
    temp.entradas = 0;
    for (int v = 0; v < g->vertices; v++) {
        temp.dist[v] = -1;
        temp.pred[v] = -1;
        temp.inicializados++;
    }
    temp.dist[origem] = 0;
    temp.ordem[0] = origem;
    fila[fim++] = origem;
    temp.quantidade = fim;
    while (inicio < fim) {
        int u = fila[inicio++];
        const GrafoArco *p = gl_vizinhos(g, u);
        temp.listas++;
        while (p != NULL) {
            int v = p->destino;
            temp.entradas++;
            if (v < 0 || v >= g->vertices || p->estado < 1 || p->estado > 2) {
                return BFS_INVALIDO;
            }
            if (p->estado == GR_ABERTA && temp.dist[v] == -1) {
                if (fim >= g->vertices || fim >= GR_CAP) {
                    return BFS_LIMITE;
                }
                temp.dist[v] = temp.dist[u] + 1;
                temp.pred[v] = u;
                fila[fim] = v;
                temp.ordem[fim] = v;
                fim++;
                temp.quantidade = fim;
            }
            p = p->prox;
        }
    }
    publicar(saida, &temp);
    return BFS_OK;
}

int bfs_caminho(const BfsResultado *r, int destino, int *caminho,
                int capacidade, int *tamanho)
{
    int reverso[GR_CAP];
    int n = 0, v;
    if (r == NULL || caminho == NULL || tamanho == NULL ||
        r->vertices < 1 || r->vertices > GR_CAP ||
        r->origem < 0 || r->origem >= r->vertices ||
        r->quantidade < 1 || r->quantidade > r->vertices ||
        destino < 0 || destino >= r->vertices ||
        capacidade < 1 || capacidade > GR_CAP) {
        return BFS_INVALIDO;
    }
    if (r->dist[destino] == -1) {
        return BFS_SEM_CAMINHO;
    }
    if (r->dist[destino] < 0 || r->dist[destino] >= r->vertices) {
        return BFS_INVALIDO;
    }
    v = destino;
    for (;;) {
        int pai;
        if (n >= r->vertices || v < 0 || v >= r->vertices) {
            return BFS_INVALIDO;
        }
        reverso[n++] = v;
        if (v == r->origem) {
            if (r->dist[v] != 0 || r->pred[v] != -1) {
                return BFS_INVALIDO;
            }
            break;
        }
        if (r->dist[v] <= 0) {
            return BFS_INVALIDO;
        }
        pai = r->pred[v];
        if (pai < 0 || pai >= r->vertices || r->dist[pai] != r->dist[v] - 1) {
            return BFS_INVALIDO;
        }
        v = pai;
    }
    if (n > capacidade) {
        return BFS_LIMITE;
    }
    for (int i = 0; i < n; i++) {
        caminho[i] = reverso[n - 1 - i];
    }
    *tamanho = n;
    return BFS_OK;
}

bfs.h

#ifndef BFS_H
#define BFS_H
#include "grafos.h"
#include <stddef.h>

#define BFS_OK 1
#define BFS_SEM_CAMINHO 0
#define BFS_INVALIDO (-1)
#define BFS_LIMITE (-2)

typedef struct {
    int vertices;
    int origem;
    int quantidade;
    int dist[GR_CAP];
    int pred[GR_CAP];
    int ordem[GR_CAP];
    size_t inicializados;
    size_t listas;
    size_t entradas;
} BfsResultado;

int bfs_executar(const GrafoLista *g, int origem, BfsResultado *saida);
int bfs_caminho(const BfsResultado *r, int destino, int *caminho,
                int capacidade, int *tamanho);
#endif

campanha_demo.c

#include "grafos.h"
#include "bfs.h"
#include "fila.h"
#include "hash.h"
#include <stdio.h>

#define PEDIDOS_MAX 8

typedef struct {
    int id, destino, status, comando;
    int quantidade, rota[GR_CAP];
} Solicitacao;

typedef struct {
    GrafoLista mapa;
    HashTabela itens;
    Fila *comandos;
    int cadastrado[GR_CAP];
    Solicitacao pedidos[PEDIDOS_MAX];
    int usados;
} Campanha;

static void destruir(Campanha *c)
{
    fila_destruir(&c->comandos);
    gl_destruir(&c->mapa);
    hash_destruir(&c->itens);
}

static int iniciar(Campanha *c)
{
    HashRegistro marca = {0, "Marca", 1};
    size_t comparacoes;
    c->comandos = NULL;
    c->usados = 0;
    for (int i = 0; i < GR_CAP; i++) {
        c->cadastrado[i] = 0;
    }
    (void)gl_iniciar(&c->mapa, GR_CAP, 0);
    hash_iniciar(&c->itens);
    if (fila_criar(&c->comandos, 4) != FILA_OK ||
        hash_inserir(&c->itens, marca, &comparacoes) != HASH_OK) {
        destruir(c);
        return 0;
    }
    return 1;
}

static int posto(const Campanha *c, int v)
{
    return v >= 0 && v < GR_CAP && c->cadastrado[v];
}

static int planejar(const Campanha *c, int destino, int *rota, int *n)
{
    BfsResultado resultado;
    if (!posto(c, 0) || !posto(c, destino) ||
        bfs_executar(&c->mapa, 0, &resultado) != BFS_OK) {
        return BFS_INVALIDO;
    }
    return bfs_caminho(&resultado, destino, rota, GR_CAP, n);
}

static void imprimir_rota(const int *rota, int n)
{
    if (n == 0) {
        printf(" sem-plano");
    }
    for (int i = 0; i < n; i++) {
        printf(" %c", 'A' + rota[i]);
    }
}

static Solicitacao *pedido(Campanha *c, int id)
{
    if (id < 1 || id > c->usados) {
        return NULL;
    }
    return &c->pedidos[id - 1];
}

static void consultar(Campanha *c, int destino)
{
    int rota[GR_CAP], n = 0;
    int codigo = planejar(c, destino, rota, &n);
    if (codigo == BFS_OK) {
        printf("Consulta:");
        imprimir_rota(rota, n);
        printf("; arestas=%d.\n", n - 1);
    } else if (codigo == BFS_SEM_CAMINHO) {
        puts("Consulta: destino nao alcancado.");
    } else {
        puts("Consulta recusada: cadastro invalido.");
    }
}

static void mostrar_pedido(const Solicitacao *p)
{
    printf("P%d A->%c status=%s comando=%d plano:", p->id, 'A' + p->destino,
           p->status == 1 ? "pendente" : "feito", p->comando);
    imprimir_rota(p->rota, p->quantidade);
    putchar('\n');
}

static void criar_pedido(Campanha *c, int destino)
{
    Solicitacao novo = {0};
    int codigo;
    if (c->usados == PEDIDOS_MAX || !posto(c, 0) || !posto(c, destino)) {
        puts("Pedido recusado: cadastro ou limite.");
        return;
    }
    novo.id = c->usados + 1;
    novo.destino = destino;
    novo.status = novo.comando = 1;
    codigo = planejar(c, destino, novo.rota, &novo.quantidade);
    if (codigo != BFS_OK && codigo != BFS_SEM_CAMINHO) {
        puts("Pedido recusado: falha no plano.");
        return;
    }
    codigo = fila_entrar(c->comandos, novo.id);
    if (codigo != FILA_OK) {
        printf("Pedido recusado: fila codigo=%d.\n", codigo);
        return;
    }
    c->pedidos[c->usados] = novo;
    c->usados++;
    mostrar_pedido(&novo);
}

static void replanejar(Campanha *c, int id)
{
    Solicitacao *p = pedido(c, id);
    int rota[GR_CAP], n = 0;
    if (p == NULL || p->status != 1 ||
        planejar(c, p->destino, rota, &n) != BFS_OK) {
        puts("Replanejamento recusado; plano anterior conservado.");
        return;
    }
    for (int i = 0; i < n; i++) {
        p->rota[i] = rota[i];
    }
    p->quantidade = n;
    printf("Replanejado P%d:", id);
    imprimir_rota(p->rota, n);
    putchar('\n');
}

static void processar(Campanha *c)
{
    int id, retirado;
    Solicitacao *p;
    if (fila_consultar(c->comandos, 0, &id) != FILA_OK) {
        puts("Fila vazia; nada processado.");
        return;
    }
    p = pedido(c, id);
    if (p == NULL || p->status != 1 || p->comando != 1) {
        puts("Estado incoerente; comando conservado.");
        return;
    }
    if (p->quantidade < 1) {
        printf("Recusa P%d: sem plano; comando mantido.\n", id);
        return;
    }
    if (p->quantidade > GR_CAP || p->rota[0] != 0 ||
        p->rota[p->quantidade - 1] != p->destino) {
        puts("Plano incoerente; comando conservado.");
        return;
    }
    for (int i = 0; i < p->quantidade; i++) {
        if (!posto(c, p->rota[i])) {
            printf("Recusa P%d: cadastro do plano; comando mantido.\n", id);
            return;
        }
    }
    for (int i = 1; i < p->quantidade; i++) {
        int u = p->rota[i - 1], v = p->rota[i];
        if (gl_estado(&c->mapa, u, v) != GR_ABERTA) {
            printf("Recusa P%d: %c-%c indisponivel; comando mantido.\n",
                   id, 'A' + u, 'A' + v);
            return;
        }
    }
    if (fila_sair(c->comandos, &retirado) != FILA_OK) {
        puts("Falha interna de fila.");
        return;
    }
    p->status = 2;
    p->comando = 0;
    printf("Executado P%d:", retirado);
    imprimir_rota(p->rota, p->quantidade);
    putchar('\n');
}

static void listar(const Campanha *c)
{
    printf("Postos:");
    for (int v = 0; v < GR_CAP; v++) {
        if (c->cadastrado[v]) {
            printf(" %c", 'A' + v);
        }
    }
    printf("\nFila:");
    for (size_t i = 0; i < fila_tamanho(c->comandos); i++) {
        int id;
        if (fila_consultar(c->comandos, (int)i, &id) == FILA_OK) {
            printf(" %d", id);
        }
    }
    putchar('\n');
    for (int i = 0; i < c->usados; i++) {
        mostrar_pedido(&c->pedidos[i]);
    }
}

static void resumir(const Campanha *c)
{
    int feitos = 0;
    for (int i = 0; i < c->usados; i++) {
        feitos += c->pedidos[i].status == 2;
    }
    printf("Encerramento parcial: feitos=%d pendentes=%d; isolados preservados.\n",
           feitos, c->usados - feitos);
}

static int ler(int valores[3])
{
    char linha[80];
    size_t n = 0, i = 0;
    int ch, ruim = 0, partes = 0;
    const int aridade[13] = {1,2,3,2,2,2,1,2,3,1,2,3,3};
    while ((ch = fgetc(stdin)) != EOF && ch != '\n') {
        if (ch < 32 || ch > 126 || n >= sizeof linha - 1) {
            ruim = 1;
        } else {
            linha[n++] = (char)ch;
        }
    }
    if (ch == EOF && ferror(stdin)) {
        return -2;
    }
    if (ch == EOF && n == 0 && !ruim) {
        return 0;
    }
    if (ch == EOF || ruim) {
        return -1;
    }
    linha[n] = '\0';
    while (i < n) {
        int valor = 0, digitos = 0;
        while (i < n && linha[i] == ' ') {
            i++;
        }
        if (i == n) {
            break;
        }
        if (partes == 3) {
            return -1;
        }
        while (i < n && linha[i] >= '0' && linha[i] <= '9') {
            if (digitos == 2) {
                return -1;
            }
            valor = valor * 10 + (linha[i] - '0');
            digitos++;
            i++;
        }
        if (digitos == 0 || (i < n && linha[i] != ' ')) {
            return -1;
        }
        valores[partes++] = valor;
    }
    if (partes == 0 || valores[0] > 12 || partes != aridade[valores[0]]) {
        return -1;
    }
    return 1;
}

int main(void)
{
    Campanha c;
    int valores[3], status = 0;
    if (!iniciar(&c)) {
        puts("Montagem recusada; recursos obtidos foram liberados.");
        return 1;
    }
    puts("Campanha pronta: simulacao, 8 slots, 8 pedidos, fila 4.");
    for (;;) {
        int leitura = ler(valores);
        int op, a = 0, b = 0;
        if (leitura == -2) {
            puts("Falha de leitura; encerrar sem executar linha.");
            status = 1;
            break;
        }
        if (leitura == 0) {
            puts("EOF: encerrar.");
            break;
        }
        if (leitura < 0) {
            puts("Entrada invalida; estado preservado.");
            continue;
        }
        op = valores[0];
        if (op == 0) {
            puts("Saida voluntaria.");
            break;
        }
        if (op == 1 || op == 3 || op == 4 || op == 5 || op == 7 || op == 10) {
            a = valores[1];
        } else if (op == 2 || op == 8 || op == 11 || op == 12) {
            a = valores[1];
            b = valores[2];
        }
        switch (op) {
        case 1:
            if (a >= GR_CAP || c.cadastrado[a]) {
                puts("Cadastro recusado.");
            } else {
                c.cadastrado[a] = 1;
                printf("Posto %c cadastrado.\n", 'A' + a);
            }
            break;
        case 2:
        case 8:
        case 12:
            if (!posto(&c, a) || !posto(&c, b)) {
                puts("Rota recusada: cadastro invalido.");
            } else {
                int codigo = op == 2 ? gl_adicionar(&c.mapa, a, b, 1) :
                    gl_disponivel(&c.mapa, a, b, op == 12);
                printf("Rota %c-%c op=%d codigo=%d.\n", 'A' + a, 'A' + b,
                       op, codigo);
            }
            break;
        case 3:
            consultar(&c, a);
            break;
        case 4:
            criar_pedido(&c, a);
            break;
        case 5: {
            const Solicitacao *p = pedido(&c, a);
            if (p == NULL) {
                puts("Pedido ausente.");
            } else {
                mostrar_pedido(p);
            }
            break;
        }
        case 6:
            processar(&c);
            break;
        case 7:
            replanejar(&c, a);
            break;
        case 9:
            listar(&c);
            break;
        case 10: {
            HashRegistro item;
            size_t comparacoes;
            if (hash_buscar(&c.itens, a, &item, &comparacoes) == HASH_OK) {
                printf("Item %d %s quantidade=%d.\n", item.chave,
                       item.nome, item.quantidade);
            } else {
                puts("Item ausente.");
            }
            break;
        }
        case 11: {
            HashRegistro item = {0, "Item", 0};
            size_t comparacoes;
            item.chave = a;
            item.quantidade = b;
            printf("Item inserir codigo=%d.\n",
                   hash_inserir(&c.itens, item, &comparacoes));
            break;
        }
        }
    }
    resumir(&c);
    destruir(&c);
    int limpo = c.comandos == NULL && c.itens.tamanho == 0;
    for (int i = 0; i < GR_CAP; i++) if (c.mapa.cabeca[i] != NULL) limpo = 0;
    for (int i = 0; i < HASH_BUCKETS; i++) if (c.itens.buckets[i] != NULL) limpo = 0;
    printf("Donos reinicializados apos limpeza: %d\n", limpo);
    if (!limpo) return 1;
    puts("Sessao encerrada; donos liberados.");
    return status;
}

fila.c

#include "fila.h"
#include <stdint.h>
#include <stdlib.h>

struct Fila {
    int *dados;
    size_t inicio;
    size_t tamanho;
    size_t capacidade;
};

int fila_criar(Fila **dona, size_t capacidade)
{
    Fila *nova;
    if (dona == NULL || *dona != NULL || capacidade == 0 ||
        capacidade > 32 || capacidade > SIZE_MAX / sizeof(int)) {
        return FILA_INVALIDO;
    }
    nova = malloc(sizeof *nova);
    if (nova == NULL) {
        return FILA_MEMORIA;
    }
    nova->dados = NULL;
    nova->inicio = 0;
    nova->tamanho = 0;
    nova->capacidade = capacidade;
    nova->dados = malloc(capacidade * sizeof *nova->dados);
    if (nova->dados == NULL) {
        free(nova);
        return FILA_MEMORIA;
    }
    *dona = nova;
    return FILA_OK;
}

int fila_entrar(Fila *f, int valor)
{
    size_t posicao;
    if (f == NULL) {
        return FILA_INVALIDO;
    }
    if (f->tamanho == f->capacidade) {
        return FILA_CHEIA;
    }
    posicao = (f->inicio + f->tamanho) % f->capacidade;
    f->dados[posicao] = valor;
    f->tamanho++;
    return FILA_OK;
}

int fila_sair(Fila *f, int *saida)
{
    int valor;
    if (f == NULL || saida == NULL) {
        return FILA_INVALIDO;
    }
    if (f->tamanho == 0) {
        return FILA_VAZIA;
    }
    valor = f->dados[f->inicio];
    f->inicio = (f->inicio + 1) % f->capacidade;
    f->tamanho--;
    *saida = valor;
    return FILA_OK;
}

int fila_consultar(const Fila *f, int posicao, int *saida)
{
    size_t i;
    if (f == NULL || saida == NULL) {
        return FILA_INVALIDO;
    }
    if (posicao < 0) {
        return FILA_POSICAO;
    }
    i = (size_t)posicao;
    if (i >= f->tamanho) {
        return FILA_POSICAO;
    }
    *saida = f->dados[(f->inicio + i) % f->capacidade];
    return FILA_OK;
}

size_t fila_inicio(const Fila *f)
{
    return f->inicio;
}

size_t fila_tamanho(const Fila *f)
{
    return f->tamanho;
}

size_t fila_capacidade(const Fila *f)
{
    return f->capacidade;
}

void fila_destruir(Fila **dona)
{
    if (dona == NULL || *dona == NULL) {
        return;
    }
    free((*dona)->dados);
    free(*dona);
    *dona = NULL;
}

fila.h

#ifndef FILA_H
#define FILA_H
#include <stddef.h>

#define FILA_OK 1
#define FILA_VAZIA 0
#define FILA_INVALIDO (-1)
#define FILA_CHEIA (-2)
#define FILA_MEMORIA (-3)
#define FILA_POSICAO (-4)

typedef struct Fila Fila;

int fila_criar(Fila **dona, size_t capacidade);
int fila_entrar(Fila *f, int valor);
int fila_sair(Fila *f, int *saida);
int fila_consultar(const Fila *f, int posicao, int *saida);
size_t fila_inicio(const Fila *f);
size_t fila_tamanho(const Fila *f);
size_t fila_capacidade(const Fila *f);
void fila_destruir(Fila **dona);
#endif

grafos.c

#include "grafos.h"
#include <stddef.h>
#include <stdlib.h>

static int configuracao(int n, int dirigido)
{
    return n >= 0 && n <= GR_CAP && (dirigido == 0 || dirigido == 1);
}

static int indice(int n, int v)
{
    return v >= 0 && v < n;
}

static int forma_m(const GrafoMatriz *g)
{
    return g != NULL && configuracao(g->vertices, g->dirigido);
}

static int forma_l(const GrafoLista *g)
{
    return g != NULL && configuracao(g->vertices, g->dirigido);
}

int gm_iniciar(GrafoMatriz *g, int n, int dirigido)
{
    if (g == NULL || !configuracao(n, dirigido)) {
        return GR_INVALIDO;
    }
    for (int u = 0; u < GR_CAP; u++) {
        for (int v = 0; v < GR_CAP; v++) {
            g->aresta[u][v] = 0;
        }
    }
    g->vertices = n;
    g->dirigido = dirigido;
    return GR_OK;
}

int gm_estado(const GrafoMatriz *g, int u, int v)
{
    if (!forma_m(g) || !indice(g->vertices, u) || !indice(g->vertices, v)) {
        return GR_INVALIDO;
    }
    return g->aresta[u][v];
}

int gm_adicionar(GrafoMatriz *g, int u, int v, int disponivel)
{
    if (gm_estado(g, u, v) < 0 || u == v ||
        (disponivel != 0 && disponivel != 1)) {
        return GR_INVALIDO;
    }
    if (g->aresta[u][v] != 0) {
        return GR_DUPLICADA;
    }
    g->aresta[u][v] = disponivel ? GR_ABERTA : GR_FECHADA;
    if (!g->dirigido) {
        g->aresta[v][u] = g->aresta[u][v];
    }
    return GR_OK;
}

int gm_remover(GrafoMatriz *g, int u, int v)
{
    int estado = gm_estado(g, u, v);
    if (estado < 0 || u == v) {
        return GR_INVALIDO;
    }
    if (estado == 0) {
        return GR_AUSENTE;
    }
    g->aresta[u][v] = 0;
    if (!g->dirigido) {
        g->aresta[v][u] = 0;
    }
    return GR_OK;
}

int gm_disponivel(GrafoMatriz *g, int u, int v, int disponivel)
{
    int estado = gm_estado(g, u, v);
    if (estado < 0 || (disponivel != 0 && disponivel != 1)) {
        return GR_INVALIDO;
    }
    if (estado == 0) {
        return GR_AUSENTE;
    }
    g->aresta[u][v] = disponivel ? GR_ABERTA : GR_FECHADA;
    if (!g->dirigido) {
        g->aresta[v][u] = g->aresta[u][v];
    }
    return GR_OK;
}

int gm_conferir(const GrafoMatriz *g)
{
    if (!forma_m(g)) {
        return 0;
    }
    for (int u = 0; u < GR_CAP; u++) {
        for (int v = 0; v < GR_CAP; v++) {
            int e = g->aresta[u][v];
            if (e < 0 || e > 2 || (u == v && e != 0) ||
                ((u >= g->vertices || v >= g->vertices) && e != 0) ||
                (!g->dirigido && e != g->aresta[v][u])) {
                return 0;
            }
        }
    }
    return 1;
}

int gl_iniciar(GrafoLista *g, int n, int dirigido)
{
    if (g == NULL || !configuracao(n, dirigido)) {
        return GR_INVALIDO;
    }
    for (int u = 0; u < GR_CAP; u++) {
        g->cabeca[u] = NULL;
    }
    g->vertices = n;
    g->dirigido = dirigido;
    return GR_OK;
}

static GrafoArco **posicao(GrafoLista *g, int u, int v)
{
    GrafoArco **p = &g->cabeca[u];
    while (*p != NULL && (*p)->destino < v) {
        p = &(*p)->prox;
    }
    return p;
}

const GrafoArco *gl_vizinhos(const GrafoLista *g, int u)
{
    if (!forma_l(g) || !indice(g->vertices, u)) {
        return NULL;
    }
    return g->cabeca[u];
}

int gl_estado(const GrafoLista *g, int u, int v)
{
    const GrafoArco *p;
    if (!forma_l(g) || !indice(g->vertices, u) || !indice(g->vertices, v)) {
        return GR_INVALIDO;
    }
    p = g->cabeca[u];
    while (p != NULL && p->destino < v) {
        p = p->prox;
    }
    return p != NULL && p->destino == v ? p->estado : GR_AUSENTE;
}

int gl_adicionar(GrafoLista *g, int u, int v, int disponivel)
{
    GrafoArco **pu, **pv = NULL;
    GrafoArco *a, *b = NULL;
    int estado;
    if (gl_estado(g, u, v) < 0 || u == v ||
        (disponivel != 0 && disponivel != 1)) {
        return GR_INVALIDO;
    }
    pu = posicao(g, u, v);
    if (*pu != NULL && (*pu)->destino == v) {
        return GR_DUPLICADA;
    }
    if (!g->dirigido) {
        pv = posicao(g, v, u);
        if (*pv != NULL && (*pv)->destino == u) {
            return GR_INVALIDO;
        }
    }
    a = malloc(sizeof *a);
    if (a == NULL) {
        return GR_MEMORIA;
    }
    if (!g->dirigido) {
        b = malloc(sizeof *b);
        if (b == NULL) {
            free(a);
            return GR_MEMORIA;
        }
    }
    estado = disponivel ? GR_ABERTA : GR_FECHADA;
    a->destino = v;
    a->estado = estado;
    a->prox = *pu;
    if (b != NULL) {
        b->destino = u;
        b->estado = estado;
        b->prox = *pv;
    }
    *pu = a;
    if (b != NULL) {
        *pv = b;
    }
    return GR_OK;
}

int gl_remover(GrafoLista *g, int u, int v)
{
    GrafoArco **pu, **pv = NULL;
    GrafoArco *a, *b = NULL;
    int estado = gl_estado(g, u, v);
    if (estado < 0 || u == v) {
        return GR_INVALIDO;
    }
    if (estado == 0) {
        return GR_AUSENTE;
    }
    pu = posicao(g, u, v);
    if (!g->dirigido) {
        pv = posicao(g, v, u);
        if (*pv == NULL || (*pv)->destino != u) {
            return GR_INVALIDO;
        }
        b = *pv;
    }
    a = *pu;
    *pu = a->prox;
    if (b != NULL) {
        *pv = b->prox;
    }
    free(a);
    if (b != NULL) {
        free(b);
    }
    return GR_OK;
}

int gl_disponivel(GrafoLista *g, int u, int v, int disponivel)
{
    GrafoArco **pu, **pv = NULL;
    int estado = gl_estado(g, u, v);
    if (estado < 0 || (disponivel != 0 && disponivel != 1)) {
        return GR_INVALIDO;
    }
    if (estado == 0) {
        return GR_AUSENTE;
    }
    pu = posicao(g, u, v);
    if (!g->dirigido) {
        pv = posicao(g, v, u);
        if (*pv == NULL || (*pv)->destino != u) {
            return GR_INVALIDO;
        }
    }
    (*pu)->estado = disponivel ? GR_ABERTA : GR_FECHADA;
    if (pv != NULL) {
        (*pv)->estado = (*pu)->estado;
    }
    return GR_OK;
}

int gl_grau(const GrafoLista *g, int u)
{
    const GrafoArco *p;
    int grau = 0;
    if (!forma_l(g) || !indice(g->vertices, u)) {
        return GR_INVALIDO;
    }
    p = g->cabeca[u];
    while (p != NULL) {
        grau++;
        p = p->prox;
    }
    return grau;
}

int gl_conferir(const GrafoLista *g)
{
    int visto[GR_CAP][GR_CAP] = {{0}};
    int total = 0;
    if (!forma_l(g)) {
        return 0;
    }
    for (int u = 0; u < GR_CAP; u++) {
        const GrafoArco *p = g->cabeca[u];
        int anterior = -1;
        if (u >= g->vertices && p != NULL) {
            return 0;
        }
        while (p != NULL) {
            if (total >= GR_CAP * (GR_CAP - 1) ||
                !indice(g->vertices, p->destino) || p->destino == u ||
                p->destino <= anterior || p->estado < 1 || p->estado > 2) {
                return 0;
            }
            visto[u][p->destino] = p->estado;
            anterior = p->destino;
            total++;
            p = p->prox;
        }
    }
    if (!g->dirigido) {
        for (int u = 0; u < g->vertices; u++) {
            for (int v = 0; v < g->vertices; v++) {
                if (visto[u][v] != visto[v][u]) {
                    return 0;
                }
            }
        }
    }
    return 1;
}

void gl_destruir(GrafoLista *g)
{
    if (g == NULL) {
        return;
    }
    for (int u = 0; u < GR_CAP; u++) {
        while (g->cabeca[u] != NULL) {
            GrafoArco *p = g->cabeca[u];
            g->cabeca[u] = p->prox;
            free(p);
        }
    }
    g->vertices = 0;
    g->dirigido = 0;
}

int gl_converter(const GrafoMatriz *origem, GrafoLista *destino)
{
    GrafoLista temporario;
    if (!gm_conferir(origem) || !forma_l(destino)) {
        return GR_INVALIDO;
    }
    (void)gl_iniciar(&temporario, origem->vertices, origem->dirigido);
    for (int u = 0; u < origem->vertices; u++) {
        for (int v = 0; v < origem->vertices; v++) {
            int estado = origem->aresta[u][v];
            if (estado != 0 && (origem->dirigido || u < v)) {
                int r = gl_adicionar(&temporario, u, v, estado == GR_ABERTA);
                if (r != GR_OK) {
                    gl_destruir(&temporario);
                    return r;
                }
            }
        }
    }
    gl_destruir(destino);
    *destino = temporario;
    (void)gl_iniciar(&temporario, 0, 0);
    return GR_OK;
}

grafos.h

#ifndef GRAFOS_H
#define GRAFOS_H

#define GR_CAP 8
#define GR_OK 1
#define GR_AUSENTE 0
#define GR_INVALIDO (-1)
#define GR_DUPLICADA (-2)
#define GR_MEMORIA (-3)
#define GR_FECHADA 1
#define GR_ABERTA 2

typedef struct {
    int vertices;
    int dirigido;
    int aresta[GR_CAP][GR_CAP];
} GrafoMatriz;

typedef struct GrafoArco {
    int destino;
    int estado;
    struct GrafoArco *prox;
} GrafoArco;

typedef struct {
    int vertices;
    int dirigido;
    GrafoArco *cabeca[GR_CAP];
} GrafoLista;

int gm_iniciar(GrafoMatriz *g, int vertices, int dirigido);
int gm_estado(const GrafoMatriz *g, int u, int v);
int gm_adicionar(GrafoMatriz *g, int u, int v, int disponivel);
int gm_remover(GrafoMatriz *g, int u, int v);
int gm_disponivel(GrafoMatriz *g, int u, int v, int disponivel);
int gm_conferir(const GrafoMatriz *g);
int gl_iniciar(GrafoLista *g, int vertices, int dirigido);
int gl_estado(const GrafoLista *g, int u, int v);
int gl_adicionar(GrafoLista *g, int u, int v, int disponivel);
int gl_remover(GrafoLista *g, int u, int v);
int gl_disponivel(GrafoLista *g, int u, int v, int disponivel);
const GrafoArco *gl_vizinhos(const GrafoLista *g, int u);
int gl_grau(const GrafoLista *g, int u);
int gl_conferir(const GrafoLista *g);
int gl_converter(const GrafoMatriz *origem, GrafoLista *destino);
void gl_destruir(GrafoLista *g);
#endif

hash.c

#include "hash.h"
#include <stdio.h>
#include <stdlib.h>

struct HashNo {
    HashRegistro dado;
    struct HashNo *prox;
};

static int forma(const HashTabela *t)
{
    return t != NULL && t->tamanho <= HASH_MAX_NOS;
}

static int chave_valida(int chave)
{
    return chave >= 0 && chave <= 99;
}

static size_t indice(int chave)
{
    return (size_t)(chave % HASH_BUCKETS);
}

static int dado_valido(HashRegistro d)
{
    if (!chave_valida(d.chave) || d.quantidade < 0 || d.quantidade > 100) {
        return 0;
    }
    for (size_t i = 0; i < sizeof d.nome; i++) {
        if (d.nome[i] == '\0') {
            return i > 0;
        }
        if (d.nome[i] < ' ' || d.nome[i] > '~') {
            return 0;
        }
    }
    return 0;
}

void hash_iniciar(HashTabela *t)
{
    if (t == NULL) {
        return;
    }
    for (size_t i = 0; i < HASH_BUCKETS; i++) {
        t->buckets[i] = NULL;
    }
    t->tamanho = 0;
}

int hash_inserir(HashTabela *t, HashRegistro dado, size_t *comparacoes)
{
    HashNo **ligacao;
    HashNo *novo;
    if (!forma(t) || comparacoes == NULL || !dado_valido(dado)) {
        return HASH_INVALIDO;
    }
    *comparacoes = 0;
    ligacao = &t->buckets[indice(dado.chave)];
    while (*ligacao != NULL) {
        (*comparacoes)++;
        if ((*ligacao)->dado.chave == dado.chave) {
            return HASH_DUPLICADO;
        }
        ligacao = &(*ligacao)->prox;
    }
    if (t->tamanho == HASH_MAX_NOS) {
        return HASH_LIMITE;
    }
    novo = malloc(sizeof *novo);
    if (novo == NULL) {
        return HASH_MEMORIA;
    }
    novo->dado = dado;
    novo->prox = NULL;
    *ligacao = novo;
    t->tamanho++;
    return HASH_OK;
}

int hash_buscar(const HashTabela *t, int chave, HashRegistro *saida,
                size_t *comparacoes)
{
    const HashNo *p;
    if (!forma(t) || !chave_valida(chave) || saida == NULL ||
        comparacoes == NULL) {
        return HASH_INVALIDO;
    }
    *comparacoes = 0;
    p = t->buckets[indice(chave)];
    while (p != NULL) {
        (*comparacoes)++;
        if (p->dado.chave == chave) {
            *saida = p->dado;
            return HASH_OK;
        }
        p = p->prox;
    }
    return HASH_AUSENTE;
}

int hash_remover(HashTabela *t, int chave, HashRegistro *saida,
                 size_t *comparacoes)
{
    HashNo **ligacao;
    if (!forma(t) || !chave_valida(chave) || saida == NULL ||
        comparacoes == NULL) {
        return HASH_INVALIDO;
    }
    *comparacoes = 0;
    ligacao = &t->buckets[indice(chave)];
    while (*ligacao != NULL) {
        HashNo *p = *ligacao;
        (*comparacoes)++;
        if (p->dado.chave == chave) {
            HashRegistro original = p->dado;
            *ligacao = p->prox;
            free(p);
            t->tamanho--;
            *saida = original;
            return HASH_OK;
        }
        ligacao = &p->prox;
    }
    return HASH_AUSENTE;
}

int hash_conferir(const HashTabela *t)
{
    int vistos[100] = {0};
    size_t total = 0;
    if (!forma(t)) {
        return 0;
    }
    for (size_t i = 0; i < HASH_BUCKETS; i++) {
        const HashNo *p = t->buckets[i];
        while (p != NULL) {
            if (total >= HASH_MAX_NOS || !dado_valido(p->dado)) {
                return 0;
            }
            if (indice(p->dado.chave) != i || vistos[p->dado.chave]) {
                return 0;
            }
            vistos[p->dado.chave] = 1;
            total++;
            p = p->prox;
        }
    }
    return total == t->tamanho;
}

void hash_listar(const HashTabela *t)
{
    for (size_t i = 0; i < HASH_BUCKETS; i++) {
        const HashNo *p = t->buckets[i];
        printf("[%zu]", i);
        while (p != NULL) {
            printf(" %d:%s:%d", p->dado.chave, p->dado.nome,
                   p->dado.quantidade);
            p = p->prox;
        }
        putchar('\n');
    }
}

void hash_relatar(const HashTabela *t)
{
    size_t maior = 0;
    size_t vazios = 0;
    for (size_t i = 0; i < HASH_BUCKETS; i++) {
        size_t n = 0;
        const HashNo *p = t->buckets[i];
        while (p != NULL) {
            n++;
            p = p->prox;
        }
        if (n == 0) {
            vazios++;
        }
        if (n > maior) {
            maior = n;
        }
    }
    printf("n=%zu carga=%.1f maior=%zu vazios=%zu\n", t->tamanho,
           (double)t->tamanho / HASH_BUCKETS, maior, vazios);
}

void hash_destruir(HashTabela *t)
{
    if (t == NULL) {
        return;
    }
    for (size_t i = 0; i < HASH_BUCKETS; i++) {
        while (t->buckets[i] != NULL) {
            HashNo *p = t->buckets[i];
            t->buckets[i] = p->prox;
            free(p);
        }
    }
    t->tamanho = 0;
}

hash.h

#ifndef HASH_H
#define HASH_H
#include <stddef.h>

#define HASH_BUCKETS 5
#define HASH_MAX_NOS 16
#define HASH_OK 1
#define HASH_AUSENTE 0
#define HASH_INVALIDO (-1)
#define HASH_DUPLICADO (-2)
#define HASH_MEMORIA (-3)
#define HASH_LIMITE (-4)

typedef struct {
    int chave;
    char nome[16];
    int quantidade;
} HashRegistro;

typedef struct HashNo HashNo;
typedef struct {
    HashNo *buckets[HASH_BUCKETS];
    size_t tamanho;
} HashTabela;

void hash_iniciar(HashTabela *t);
int hash_inserir(HashTabela *t, HashRegistro dado, size_t *comparacoes);
int hash_buscar(const HashTabela *t, int chave, HashRegistro *saida,
                size_t *comparacoes);
int hash_remover(HashTabela *t, int chave, HashRegistro *saida,
                 size_t *comparacoes);
int hash_conferir(const HashTabela *t);
void hash_listar(const HashTabela *t);
void hash_relatar(const HashTabela *t);
void hash_destruir(HashTabela *t);
#endif
Editar e executar esta solução
Exemplo 1 · entrada e saída esperada

Entrada padrão

1 0
1 1
1 2
1 3
1 4
2 0 1
2 0 2
2 1 3
2 2 3
3 3
4 3
8 1 3
6
5 1
3 3
5 1
7 1
6
4 4
6
9
0

Saída esperada

Campanha pronta: simulacao, 8 slots, 8 pedidos, fila 4.
Posto A cadastrado.
Posto B cadastrado.
Posto C cadastrado.
Posto D cadastrado.
Posto E cadastrado.
Rota A-B op=2 codigo=1.
Rota A-C op=2 codigo=1.
Rota B-D op=2 codigo=1.
Rota C-D op=2 codigo=1.
Consulta: A B D; arestas=2.
P1 A->D status=pendente comando=1 plano: A B D
Rota B-D op=8 codigo=1.
Recusa P1: B-D indisponivel; comando mantido.
P1 A->D status=pendente comando=1 plano: A B D
Consulta: A C D; arestas=2.
P1 A->D status=pendente comando=1 plano: A B D
Replanejado P1: A C D
Executado P1: A C D
P2 A->E status=pendente comando=1 plano: sem-plano
Recusa P2: sem plano; comando mantido.
Postos: A B C D E
Fila: 2
P1 A->D status=feito comando=0 plano: A C D
P2 A->E status=pendente comando=1 plano: sem-plano
Saida voluntaria.
Encerramento parcial: feitos=1 pendentes=1; isolados preservados.
Donos reinicializados apos limpeza: 1
Sessao encerrada; donos liberados.

Estado de saída: 0.

Editar e testar o exemplo 1
Exemplo 2 · entrada e saída esperada

Entrada padrão

x
6
10 99
0

Saída esperada

Campanha pronta: simulacao, 8 slots, 8 pedidos, fila 4.
Entrada invalida; estado preservado.
Fila vazia; nada processado.
Item ausente.
Saida voluntaria.
Encerramento parcial: feitos=0 pendentes=0; isolados preservados.
Donos reinicializados apos limpeza: 1
Sessao encerrada; donos liberados.

Estado de saída: 0.

Editar e testar o exemplo 2

L3-C15-E12

Missão#

Conclua a campanha com um conjunto de rotas confirmadas e disponíveis, missões processadas por critérios declarados e pendências preservadas. Apresente as decisões coletivas separadamente dos cálculos; entregue o mapa, os procedimentos de manutenção e as escolhas de estruturas justificadas.

Ver uma dica

Um encerramento parcial preserva as pendências que o cálculo não resolveu.

Ver resolução comentada

A campanha executável completa abaixo usa hash para itens por ID, filaFIFO para comandos e listas de adjacência+BFS para planejar por menor número de portais. Os pedidos guardam cópias de ID/destino/plano, sem possuir nós do grafo. Não foi acrescentada uma BST sem requisito.

O mapa confirmado do roteiro tem AB,AC,BD,CD; BD é fechada antes de executar o plano antigo. O programa recusa, preserva dados, calcula A–C–D e só altera o pedido no comando explícito de replanejamento. P1é concluída; P2paraEisolado permanece pendente na fila. A mensagem final registra feitos1/pendentes1 e conserva o posto isolado, sem alegar acessibilidade universal.

Comando de construção: cc -std=c17 -Wall -Wextra -Wpedantic -Werror campanha_demo.c grafos.c bfs.c fila.c hash.c -o campanha. Use o caso completo de entrada fornecido, uma instrução por linha. Comandos:1cadastrar posto;2confirmar ligação;3consultar caminho;4solicitar;5consultar pedido;6processar;7replanejar;8bloquear;9listar;10consultar item;11inserir item;12disponibilizar;0sair. Argumentos e mensagens estão no caso e no parser entregue.

Manutenção: atualizar disponibilidade a partir de informação confirmada; revalidar todas as arestas ao executar; conservar versões de planos recusados até replanejar explicitamente; revisar limites/ownership ao trocar módulos; repetir testes de coleção vazia, colisão, fechamento e pendência. O grafo possui adjacências, o hash possui seus nós/registros, a fila possui seu armazenamento e os registros de pedidos são embutidos. Destruir fila, grafo e hash encerra a sessão.

Os números de alcance e a ordemFIFO são cálculos do modelo, não decisões coletivas. Autorizações, prioridades políticas e situação de famílias e recursos continuam fora das conclusões automáticas. A entrega encerra a simulação documentada com rotas disponíveis e pendências visíveis, sem inventar uma solução global para Valdora.

bfs.c

#include "bfs.h"

static void publicar(BfsResultado *destino, const BfsResultado *origem)
{
    destino->vertices = origem->vertices;
    destino->origem = origem->origem;
    destino->quantidade = origem->quantidade;
    destino->inicializados = origem->inicializados;
    destino->listas = origem->listas;
    destino->entradas = origem->entradas;
    for (int i = 0; i < origem->vertices; i++) {
        destino->dist[i] = origem->dist[i];
        destino->pred[i] = origem->pred[i];
    }
    for (int i = 0; i < origem->quantidade; i++) {
        destino->ordem[i] = origem->ordem[i];
    }
}

int bfs_executar(const GrafoLista *g, int origem, BfsResultado *saida)
{
    BfsResultado temp;
    int fila[GR_CAP];
    int inicio = 0, fim = 0;
    if (g == NULL || saida == NULL || g->vertices < 0 || g->vertices > GR_CAP ||
        (g->dirigido != 0 && g->dirigido != 1) ||
        origem < 0 || origem >= g->vertices) {
        return BFS_INVALIDO;
    }
    temp.vertices = g->vertices;
    temp.origem = origem;
    temp.quantidade = 0;
    temp.inicializados = 0;
    temp.listas = 0;
    temp.entradas = 0;
    for (int v = 0; v < g->vertices; v++) {
        temp.dist[v] = -1;
        temp.pred[v] = -1;
        temp.inicializados++;
    }
    temp.dist[origem] = 0;
    temp.ordem[0] = origem;
    fila[fim++] = origem;
    temp.quantidade = fim;
    while (inicio < fim) {
        int u = fila[inicio++];
        const GrafoArco *p = gl_vizinhos(g, u);
        temp.listas++;
        while (p != NULL) {
            int v = p->destino;
            temp.entradas++;
            if (v < 0 || v >= g->vertices || p->estado < 1 || p->estado > 2) {
                return BFS_INVALIDO;
            }
            if (p->estado == GR_ABERTA && temp.dist[v] == -1) {
                if (fim >= g->vertices || fim >= GR_CAP) {
                    return BFS_LIMITE;
                }
                temp.dist[v] = temp.dist[u] + 1;
                temp.pred[v] = u;
                fila[fim] = v;
                temp.ordem[fim] = v;
                fim++;
                temp.quantidade = fim;
            }
            p = p->prox;
        }
    }
    publicar(saida, &temp);
    return BFS_OK;
}

int bfs_caminho(const BfsResultado *r, int destino, int *caminho,
                int capacidade, int *tamanho)
{
    int reverso[GR_CAP];
    int n = 0, v;
    if (r == NULL || caminho == NULL || tamanho == NULL ||
        r->vertices < 1 || r->vertices > GR_CAP ||
        r->origem < 0 || r->origem >= r->vertices ||
        r->quantidade < 1 || r->quantidade > r->vertices ||
        destino < 0 || destino >= r->vertices ||
        capacidade < 1 || capacidade > GR_CAP) {
        return BFS_INVALIDO;
    }
    if (r->dist[destino] == -1) {
        return BFS_SEM_CAMINHO;
    }
    if (r->dist[destino] < 0 || r->dist[destino] >= r->vertices) {
        return BFS_INVALIDO;
    }
    v = destino;
    for (;;) {
        int pai;
        if (n >= r->vertices || v < 0 || v >= r->vertices) {
            return BFS_INVALIDO;
        }
        reverso[n++] = v;
        if (v == r->origem) {
            if (r->dist[v] != 0 || r->pred[v] != -1) {
                return BFS_INVALIDO;
            }
            break;
        }
        if (r->dist[v] <= 0) {
            return BFS_INVALIDO;
        }
        pai = r->pred[v];
        if (pai < 0 || pai >= r->vertices || r->dist[pai] != r->dist[v] - 1) {
            return BFS_INVALIDO;
        }
        v = pai;
    }
    if (n > capacidade) {
        return BFS_LIMITE;
    }
    for (int i = 0; i < n; i++) {
        caminho[i] = reverso[n - 1 - i];
    }
    *tamanho = n;
    return BFS_OK;
}

bfs.h

#ifndef BFS_H
#define BFS_H
#include "grafos.h"
#include <stddef.h>

#define BFS_OK 1
#define BFS_SEM_CAMINHO 0
#define BFS_INVALIDO (-1)
#define BFS_LIMITE (-2)

typedef struct {
    int vertices;
    int origem;
    int quantidade;
    int dist[GR_CAP];
    int pred[GR_CAP];
    int ordem[GR_CAP];
    size_t inicializados;
    size_t listas;
    size_t entradas;
} BfsResultado;

int bfs_executar(const GrafoLista *g, int origem, BfsResultado *saida);
int bfs_caminho(const BfsResultado *r, int destino, int *caminho,
                int capacidade, int *tamanho);
#endif

campanha_demo.c

#include "grafos.h"
#include "bfs.h"
#include "fila.h"
#include "hash.h"
#include <stdio.h>

#define PEDIDOS_MAX 8

typedef struct {
    int id, destino, status, comando;
    int quantidade, rota[GR_CAP];
} Solicitacao;

typedef struct {
    GrafoLista mapa;
    HashTabela itens;
    Fila *comandos;
    int cadastrado[GR_CAP];
    Solicitacao pedidos[PEDIDOS_MAX];
    int usados;
} Campanha;

static void destruir(Campanha *c)
{
    fila_destruir(&c->comandos);
    gl_destruir(&c->mapa);
    hash_destruir(&c->itens);
}

static int iniciar(Campanha *c)
{
    HashRegistro marca = {0, "Marca", 1};
    size_t comparacoes;
    c->comandos = NULL;
    c->usados = 0;
    for (int i = 0; i < GR_CAP; i++) {
        c->cadastrado[i] = 0;
    }
    (void)gl_iniciar(&c->mapa, GR_CAP, 0);
    hash_iniciar(&c->itens);
    if (fila_criar(&c->comandos, 4) != FILA_OK ||
        hash_inserir(&c->itens, marca, &comparacoes) != HASH_OK) {
        destruir(c);
        return 0;
    }
    return 1;
}

static int posto(const Campanha *c, int v)
{
    return v >= 0 && v < GR_CAP && c->cadastrado[v];
}

static int planejar(const Campanha *c, int destino, int *rota, int *n)
{
    BfsResultado resultado;
    if (!posto(c, 0) || !posto(c, destino) ||
        bfs_executar(&c->mapa, 0, &resultado) != BFS_OK) {
        return BFS_INVALIDO;
    }
    return bfs_caminho(&resultado, destino, rota, GR_CAP, n);
}

static void imprimir_rota(const int *rota, int n)
{
    if (n == 0) {
        printf(" sem-plano");
    }
    for (int i = 0; i < n; i++) {
        printf(" %c", 'A' + rota[i]);
    }
}

static Solicitacao *pedido(Campanha *c, int id)
{
    if (id < 1 || id > c->usados) {
        return NULL;
    }
    return &c->pedidos[id - 1];
}

static void consultar(Campanha *c, int destino)
{
    int rota[GR_CAP], n = 0;
    int codigo = planejar(c, destino, rota, &n);
    if (codigo == BFS_OK) {
        printf("Consulta:");
        imprimir_rota(rota, n);
        printf("; arestas=%d.\n", n - 1);
    } else if (codigo == BFS_SEM_CAMINHO) {
        puts("Consulta: destino nao alcancado.");
    } else {
        puts("Consulta recusada: cadastro invalido.");
    }
}

static void mostrar_pedido(const Solicitacao *p)
{
    printf("P%d A->%c status=%s comando=%d plano:", p->id, 'A' + p->destino,
           p->status == 1 ? "pendente" : "feito", p->comando);
    imprimir_rota(p->rota, p->quantidade);
    putchar('\n');
}

static void criar_pedido(Campanha *c, int destino)
{
    Solicitacao novo = {0};
    int codigo;
    if (c->usados == PEDIDOS_MAX || !posto(c, 0) || !posto(c, destino)) {
        puts("Pedido recusado: cadastro ou limite.");
        return;
    }
    novo.id = c->usados + 1;
    novo.destino = destino;
    novo.status = novo.comando = 1;
    codigo = planejar(c, destino, novo.rota, &novo.quantidade);
    if (codigo != BFS_OK && codigo != BFS_SEM_CAMINHO) {
        puts("Pedido recusado: falha no plano.");
        return;
    }
    codigo = fila_entrar(c->comandos, novo.id);
    if (codigo != FILA_OK) {
        printf("Pedido recusado: fila codigo=%d.\n", codigo);
        return;
    }
    c->pedidos[c->usados] = novo;
    c->usados++;
    mostrar_pedido(&novo);
}

static void replanejar(Campanha *c, int id)
{
    Solicitacao *p = pedido(c, id);
    int rota[GR_CAP], n = 0;
    if (p == NULL || p->status != 1 ||
        planejar(c, p->destino, rota, &n) != BFS_OK) {
        puts("Replanejamento recusado; plano anterior conservado.");
        return;
    }
    for (int i = 0; i < n; i++) {
        p->rota[i] = rota[i];
    }
    p->quantidade = n;
    printf("Replanejado P%d:", id);
    imprimir_rota(p->rota, n);
    putchar('\n');
}

static void processar(Campanha *c)
{
    int id, retirado;
    Solicitacao *p;
    if (fila_consultar(c->comandos, 0, &id) != FILA_OK) {
        puts("Fila vazia; nada processado.");
        return;
    }
    p = pedido(c, id);
    if (p == NULL || p->status != 1 || p->comando != 1) {
        puts("Estado incoerente; comando conservado.");
        return;
    }
    if (p->quantidade < 1) {
        printf("Recusa P%d: sem plano; comando mantido.\n", id);
        return;
    }
    if (p->quantidade > GR_CAP || p->rota[0] != 0 ||
        p->rota[p->quantidade - 1] != p->destino) {
        puts("Plano incoerente; comando conservado.");
        return;
    }
    for (int i = 0; i < p->quantidade; i++) {
        if (!posto(c, p->rota[i])) {
            printf("Recusa P%d: cadastro do plano; comando mantido.\n", id);
            return;
        }
    }
    for (int i = 1; i < p->quantidade; i++) {
        int u = p->rota[i - 1], v = p->rota[i];
        if (gl_estado(&c->mapa, u, v) != GR_ABERTA) {
            printf("Recusa P%d: %c-%c indisponivel; comando mantido.\n",
                   id, 'A' + u, 'A' + v);
            return;
        }
    }
    if (fila_sair(c->comandos, &retirado) != FILA_OK) {
        puts("Falha interna de fila.");
        return;
    }
    p->status = 2;
    p->comando = 0;
    printf("Executado P%d:", retirado);
    imprimir_rota(p->rota, p->quantidade);
    putchar('\n');
}

static void listar(const Campanha *c)
{
    printf("Postos:");
    for (int v = 0; v < GR_CAP; v++) {
        if (c->cadastrado[v]) {
            printf(" %c", 'A' + v);
        }
    }
    printf("\nFila:");
    for (size_t i = 0; i < fila_tamanho(c->comandos); i++) {
        int id;
        if (fila_consultar(c->comandos, (int)i, &id) == FILA_OK) {
            printf(" %d", id);
        }
    }
    putchar('\n');
    for (int i = 0; i < c->usados; i++) {
        mostrar_pedido(&c->pedidos[i]);
    }
}

static void resumir(const Campanha *c)
{
    int feitos = 0;
    for (int i = 0; i < c->usados; i++) {
        feitos += c->pedidos[i].status == 2;
    }
    printf("Encerramento parcial: feitos=%d pendentes=%d; isolados preservados.\n",
           feitos, c->usados - feitos);
}

static int ler(int valores[3])
{
    char linha[80];
    size_t n = 0, i = 0;
    int ch, ruim = 0, partes = 0;
    const int aridade[13] = {1,2,3,2,2,2,1,2,3,1,2,3,3};
    while ((ch = fgetc(stdin)) != EOF && ch != '\n') {
        if (ch < 32 || ch > 126 || n >= sizeof linha - 1) {
            ruim = 1;
        } else {
            linha[n++] = (char)ch;
        }
    }
    if (ch == EOF && ferror(stdin)) {
        return -2;
    }
    if (ch == EOF && n == 0 && !ruim) {
        return 0;
    }
    if (ch == EOF || ruim) {
        return -1;
    }
    linha[n] = '\0';
    while (i < n) {
        int valor = 0, digitos = 0;
        while (i < n && linha[i] == ' ') {
            i++;
        }
        if (i == n) {
            break;
        }
        if (partes == 3) {
            return -1;
        }
        while (i < n && linha[i] >= '0' && linha[i] <= '9') {
            if (digitos == 2) {
                return -1;
            }
            valor = valor * 10 + (linha[i] - '0');
            digitos++;
            i++;
        }
        if (digitos == 0 || (i < n && linha[i] != ' ')) {
            return -1;
        }
        valores[partes++] = valor;
    }
    if (partes == 0 || valores[0] > 12 || partes != aridade[valores[0]]) {
        return -1;
    }
    return 1;
}

int main(void)
{
    Campanha c;
    int valores[3], status = 0;
    if (!iniciar(&c)) {
        puts("Montagem recusada; recursos obtidos foram liberados.");
        return 1;
    }
    puts("Campanha pronta: simulacao, 8 slots, 8 pedidos, fila 4.");
    for (;;) {
        int leitura = ler(valores);
        int op, a = 0, b = 0;
        if (leitura == -2) {
            puts("Falha de leitura; encerrar sem executar linha.");
            status = 1;
            break;
        }
        if (leitura == 0) {
            puts("EOF: encerrar.");
            break;
        }
        if (leitura < 0) {
            puts("Entrada invalida; estado preservado.");
            continue;
        }
        op = valores[0];
        if (op == 0) {
            puts("Saida voluntaria.");
            break;
        }
        if (op == 1 || op == 3 || op == 4 || op == 5 || op == 7 || op == 10) {
            a = valores[1];
        } else if (op == 2 || op == 8 || op == 11 || op == 12) {
            a = valores[1];
            b = valores[2];
        }
        switch (op) {
        case 1:
            if (a >= GR_CAP || c.cadastrado[a]) {
                puts("Cadastro recusado.");
            } else {
                c.cadastrado[a] = 1;
                printf("Posto %c cadastrado.\n", 'A' + a);
            }
            break;
        case 2:
        case 8:
        case 12:
            if (!posto(&c, a) || !posto(&c, b)) {
                puts("Rota recusada: cadastro invalido.");
            } else {
                int codigo = op == 2 ? gl_adicionar(&c.mapa, a, b, 1) :
                    gl_disponivel(&c.mapa, a, b, op == 12);
                printf("Rota %c-%c op=%d codigo=%d.\n", 'A' + a, 'A' + b,
                       op, codigo);
            }
            break;
        case 3:
            consultar(&c, a);
            break;
        case 4:
            criar_pedido(&c, a);
            break;
        case 5: {
            const Solicitacao *p = pedido(&c, a);
            if (p == NULL) {
                puts("Pedido ausente.");
            } else {
                mostrar_pedido(p);
            }
            break;
        }
        case 6:
            processar(&c);
            break;
        case 7:
            replanejar(&c, a);
            break;
        case 9:
            listar(&c);
            break;
        case 10: {
            HashRegistro item;
            size_t comparacoes;
            if (hash_buscar(&c.itens, a, &item, &comparacoes) == HASH_OK) {
                printf("Item %d %s quantidade=%d.\n", item.chave,
                       item.nome, item.quantidade);
            } else {
                puts("Item ausente.");
            }
            break;
        }
        case 11: {
            HashRegistro item = {0, "Item", 0};
            size_t comparacoes;
            item.chave = a;
            item.quantidade = b;
            printf("Item inserir codigo=%d.\n",
                   hash_inserir(&c.itens, item, &comparacoes));
            break;
        }
        }
    }
    resumir(&c);
    destruir(&c);
    puts("Sessao encerrada; donos liberados.");
    return status;
}

fila.c

#include "fila.h"
#include <stdint.h>
#include <stdlib.h>

struct Fila {
    int *dados;
    size_t inicio;
    size_t tamanho;
    size_t capacidade;
};

int fila_criar(Fila **dona, size_t capacidade)
{
    Fila *nova;
    if (dona == NULL || *dona != NULL || capacidade == 0 ||
        capacidade > 32 || capacidade > SIZE_MAX / sizeof(int)) {
        return FILA_INVALIDO;
    }
    nova = malloc(sizeof *nova);
    if (nova == NULL) {
        return FILA_MEMORIA;
    }
    nova->dados = NULL;
    nova->inicio = 0;
    nova->tamanho = 0;
    nova->capacidade = capacidade;
    nova->dados = malloc(capacidade * sizeof *nova->dados);
    if (nova->dados == NULL) {
        free(nova);
        return FILA_MEMORIA;
    }
    *dona = nova;
    return FILA_OK;
}

int fila_entrar(Fila *f, int valor)
{
    size_t posicao;
    if (f == NULL) {
        return FILA_INVALIDO;
    }
    if (f->tamanho == f->capacidade) {
        return FILA_CHEIA;
    }
    posicao = (f->inicio + f->tamanho) % f->capacidade;
    f->dados[posicao] = valor;
    f->tamanho++;
    return FILA_OK;
}

int fila_sair(Fila *f, int *saida)
{
    int valor;
    if (f == NULL || saida == NULL) {
        return FILA_INVALIDO;
    }
    if (f->tamanho == 0) {
        return FILA_VAZIA;
    }
    valor = f->dados[f->inicio];
    f->inicio = (f->inicio + 1) % f->capacidade;
    f->tamanho--;
    *saida = valor;
    return FILA_OK;
}

int fila_consultar(const Fila *f, int posicao, int *saida)
{
    size_t i;
    if (f == NULL || saida == NULL) {
        return FILA_INVALIDO;
    }
    if (posicao < 0) {
        return FILA_POSICAO;
    }
    i = (size_t)posicao;
    if (i >= f->tamanho) {
        return FILA_POSICAO;
    }
    *saida = f->dados[(f->inicio + i) % f->capacidade];
    return FILA_OK;
}

size_t fila_inicio(const Fila *f)
{
    return f->inicio;
}

size_t fila_tamanho(const Fila *f)
{
    return f->tamanho;
}

size_t fila_capacidade(const Fila *f)
{
    return f->capacidade;
}

void fila_destruir(Fila **dona)
{
    if (dona == NULL || *dona == NULL) {
        return;
    }
    free((*dona)->dados);
    free(*dona);
    *dona = NULL;
}

fila.h

#ifndef FILA_H
#define FILA_H
#include <stddef.h>

#define FILA_OK 1
#define FILA_VAZIA 0
#define FILA_INVALIDO (-1)
#define FILA_CHEIA (-2)
#define FILA_MEMORIA (-3)
#define FILA_POSICAO (-4)

typedef struct Fila Fila;

int fila_criar(Fila **dona, size_t capacidade);
int fila_entrar(Fila *f, int valor);
int fila_sair(Fila *f, int *saida);
int fila_consultar(const Fila *f, int posicao, int *saida);
size_t fila_inicio(const Fila *f);
size_t fila_tamanho(const Fila *f);
size_t fila_capacidade(const Fila *f);
void fila_destruir(Fila **dona);
#endif

grafos.c

#include "grafos.h"
#include <stddef.h>
#include <stdlib.h>

static int configuracao(int n, int dirigido)
{
    return n >= 0 && n <= GR_CAP && (dirigido == 0 || dirigido == 1);
}

static int indice(int n, int v)
{
    return v >= 0 && v < n;
}

static int forma_m(const GrafoMatriz *g)
{
    return g != NULL && configuracao(g->vertices, g->dirigido);
}

static int forma_l(const GrafoLista *g)
{
    return g != NULL && configuracao(g->vertices, g->dirigido);
}

int gm_iniciar(GrafoMatriz *g, int n, int dirigido)
{
    if (g == NULL || !configuracao(n, dirigido)) {
        return GR_INVALIDO;
    }
    for (int u = 0; u < GR_CAP; u++) {
        for (int v = 0; v < GR_CAP; v++) {
            g->aresta[u][v] = 0;
        }
    }
    g->vertices = n;
    g->dirigido = dirigido;
    return GR_OK;
}

int gm_estado(const GrafoMatriz *g, int u, int v)
{
    if (!forma_m(g) || !indice(g->vertices, u) || !indice(g->vertices, v)) {
        return GR_INVALIDO;
    }
    return g->aresta[u][v];
}

int gm_adicionar(GrafoMatriz *g, int u, int v, int disponivel)
{
    if (gm_estado(g, u, v) < 0 || u == v ||
        (disponivel != 0 && disponivel != 1)) {
        return GR_INVALIDO;
    }
    if (g->aresta[u][v] != 0) {
        return GR_DUPLICADA;
    }
    g->aresta[u][v] = disponivel ? GR_ABERTA : GR_FECHADA;
    if (!g->dirigido) {
        g->aresta[v][u] = g->aresta[u][v];
    }
    return GR_OK;
}

int gm_remover(GrafoMatriz *g, int u, int v)
{
    int estado = gm_estado(g, u, v);
    if (estado < 0 || u == v) {
        return GR_INVALIDO;
    }
    if (estado == 0) {
        return GR_AUSENTE;
    }
    g->aresta[u][v] = 0;
    if (!g->dirigido) {
        g->aresta[v][u] = 0;
    }
    return GR_OK;
}

int gm_disponivel(GrafoMatriz *g, int u, int v, int disponivel)
{
    int estado = gm_estado(g, u, v);
    if (estado < 0 || (disponivel != 0 && disponivel != 1)) {
        return GR_INVALIDO;
    }
    if (estado == 0) {
        return GR_AUSENTE;
    }
    g->aresta[u][v] = disponivel ? GR_ABERTA : GR_FECHADA;
    if (!g->dirigido) {
        g->aresta[v][u] = g->aresta[u][v];
    }
    return GR_OK;
}

int gm_conferir(const GrafoMatriz *g)
{
    if (!forma_m(g)) {
        return 0;
    }
    for (int u = 0; u < GR_CAP; u++) {
        for (int v = 0; v < GR_CAP; v++) {
            int e = g->aresta[u][v];
            if (e < 0 || e > 2 || (u == v && e != 0) ||
                ((u >= g->vertices || v >= g->vertices) && e != 0) ||
                (!g->dirigido && e != g->aresta[v][u])) {
                return 0;
            }
        }
    }
    return 1;
}

int gl_iniciar(GrafoLista *g, int n, int dirigido)
{
    if (g == NULL || !configuracao(n, dirigido)) {
        return GR_INVALIDO;
    }
    for (int u = 0; u < GR_CAP; u++) {
        g->cabeca[u] = NULL;
    }
    g->vertices = n;
    g->dirigido = dirigido;
    return GR_OK;
}

static GrafoArco **posicao(GrafoLista *g, int u, int v)
{
    GrafoArco **p = &g->cabeca[u];
    while (*p != NULL && (*p)->destino < v) {
        p = &(*p)->prox;
    }
    return p;
}

const GrafoArco *gl_vizinhos(const GrafoLista *g, int u)
{
    if (!forma_l(g) || !indice(g->vertices, u)) {
        return NULL;
    }
    return g->cabeca[u];
}

int gl_estado(const GrafoLista *g, int u, int v)
{
    const GrafoArco *p;
    if (!forma_l(g) || !indice(g->vertices, u) || !indice(g->vertices, v)) {
        return GR_INVALIDO;
    }
    p = g->cabeca[u];
    while (p != NULL && p->destino < v) {
        p = p->prox;
    }
    return p != NULL && p->destino == v ? p->estado : GR_AUSENTE;
}

int gl_adicionar(GrafoLista *g, int u, int v, int disponivel)
{
    GrafoArco **pu, **pv = NULL;
    GrafoArco *a, *b = NULL;
    int estado;
    if (gl_estado(g, u, v) < 0 || u == v ||
        (disponivel != 0 && disponivel != 1)) {
        return GR_INVALIDO;
    }
    pu = posicao(g, u, v);
    if (*pu != NULL && (*pu)->destino == v) {
        return GR_DUPLICADA;
    }
    if (!g->dirigido) {
        pv = posicao(g, v, u);
        if (*pv != NULL && (*pv)->destino == u) {
            return GR_INVALIDO;
        }
    }
    a = malloc(sizeof *a);
    if (a == NULL) {
        return GR_MEMORIA;
    }
    if (!g->dirigido) {
        b = malloc(sizeof *b);
        if (b == NULL) {
            free(a);
            return GR_MEMORIA;
        }
    }
    estado = disponivel ? GR_ABERTA : GR_FECHADA;
    a->destino = v;
    a->estado = estado;
    a->prox = *pu;
    if (b != NULL) {
        b->destino = u;
        b->estado = estado;
        b->prox = *pv;
    }
    *pu = a;
    if (b != NULL) {
        *pv = b;
    }
    return GR_OK;
}

int gl_remover(GrafoLista *g, int u, int v)
{
    GrafoArco **pu, **pv = NULL;
    GrafoArco *a, *b = NULL;
    int estado = gl_estado(g, u, v);
    if (estado < 0 || u == v) {
        return GR_INVALIDO;
    }
    if (estado == 0) {
        return GR_AUSENTE;
    }
    pu = posicao(g, u, v);
    if (!g->dirigido) {
        pv = posicao(g, v, u);
        if (*pv == NULL || (*pv)->destino != u) {
            return GR_INVALIDO;
        }
        b = *pv;
    }
    a = *pu;
    *pu = a->prox;
    if (b != NULL) {
        *pv = b->prox;
    }
    free(a);
    if (b != NULL) {
        free(b);
    }
    return GR_OK;
}

int gl_disponivel(GrafoLista *g, int u, int v, int disponivel)
{
    GrafoArco **pu, **pv = NULL;
    int estado = gl_estado(g, u, v);
    if (estado < 0 || (disponivel != 0 && disponivel != 1)) {
        return GR_INVALIDO;
    }
    if (estado == 0) {
        return GR_AUSENTE;
    }
    pu = posicao(g, u, v);
    if (!g->dirigido) {
        pv = posicao(g, v, u);
        if (*pv == NULL || (*pv)->destino != u) {
            return GR_INVALIDO;
        }
    }
    (*pu)->estado = disponivel ? GR_ABERTA : GR_FECHADA;
    if (pv != NULL) {
        (*pv)->estado = (*pu)->estado;
    }
    return GR_OK;
}

int gl_grau(const GrafoLista *g, int u)
{
    const GrafoArco *p;
    int grau = 0;
    if (!forma_l(g) || !indice(g->vertices, u)) {
        return GR_INVALIDO;
    }
    p = g->cabeca[u];
    while (p != NULL) {
        grau++;
        p = p->prox;
    }
    return grau;
}

int gl_conferir(const GrafoLista *g)
{
    int visto[GR_CAP][GR_CAP] = {{0}};
    int total = 0;
    if (!forma_l(g)) {
        return 0;
    }
    for (int u = 0; u < GR_CAP; u++) {
        const GrafoArco *p = g->cabeca[u];
        int anterior = -1;
        if (u >= g->vertices && p != NULL) {
            return 0;
        }
        while (p != NULL) {
            if (total >= GR_CAP * (GR_CAP - 1) ||
                !indice(g->vertices, p->destino) || p->destino == u ||
                p->destino <= anterior || p->estado < 1 || p->estado > 2) {
                return 0;
            }
            visto[u][p->destino] = p->estado;
            anterior = p->destino;
            total++;
            p = p->prox;
        }
    }
    if (!g->dirigido) {
        for (int u = 0; u < g->vertices; u++) {
            for (int v = 0; v < g->vertices; v++) {
                if (visto[u][v] != visto[v][u]) {
                    return 0;
                }
            }
        }
    }
    return 1;
}

void gl_destruir(GrafoLista *g)
{
    if (g == NULL) {
        return;
    }
    for (int u = 0; u < GR_CAP; u++) {
        while (g->cabeca[u] != NULL) {
            GrafoArco *p = g->cabeca[u];
            g->cabeca[u] = p->prox;
            free(p);
        }
    }
    g->vertices = 0;
    g->dirigido = 0;
}

int gl_converter(const GrafoMatriz *origem, GrafoLista *destino)
{
    GrafoLista temporario;
    if (!gm_conferir(origem) || !forma_l(destino)) {
        return GR_INVALIDO;
    }
    (void)gl_iniciar(&temporario, origem->vertices, origem->dirigido);
    for (int u = 0; u < origem->vertices; u++) {
        for (int v = 0; v < origem->vertices; v++) {
            int estado = origem->aresta[u][v];
            if (estado != 0 && (origem->dirigido || u < v)) {
                int r = gl_adicionar(&temporario, u, v, estado == GR_ABERTA);
                if (r != GR_OK) {
                    gl_destruir(&temporario);
                    return r;
                }
            }
        }
    }
    gl_destruir(destino);
    *destino = temporario;
    (void)gl_iniciar(&temporario, 0, 0);
    return GR_OK;
}

grafos.h

#ifndef GRAFOS_H
#define GRAFOS_H

#define GR_CAP 8
#define GR_OK 1
#define GR_AUSENTE 0
#define GR_INVALIDO (-1)
#define GR_DUPLICADA (-2)
#define GR_MEMORIA (-3)
#define GR_FECHADA 1
#define GR_ABERTA 2

typedef struct {
    int vertices;
    int dirigido;
    int aresta[GR_CAP][GR_CAP];
} GrafoMatriz;

typedef struct GrafoArco {
    int destino;
    int estado;
    struct GrafoArco *prox;
} GrafoArco;

typedef struct {
    int vertices;
    int dirigido;
    GrafoArco *cabeca[GR_CAP];
} GrafoLista;

int gm_iniciar(GrafoMatriz *g, int vertices, int dirigido);
int gm_estado(const GrafoMatriz *g, int u, int v);
int gm_adicionar(GrafoMatriz *g, int u, int v, int disponivel);
int gm_remover(GrafoMatriz *g, int u, int v);
int gm_disponivel(GrafoMatriz *g, int u, int v, int disponivel);
int gm_conferir(const GrafoMatriz *g);
int gl_iniciar(GrafoLista *g, int vertices, int dirigido);
int gl_estado(const GrafoLista *g, int u, int v);
int gl_adicionar(GrafoLista *g, int u, int v, int disponivel);
int gl_remover(GrafoLista *g, int u, int v);
int gl_disponivel(GrafoLista *g, int u, int v, int disponivel);
const GrafoArco *gl_vizinhos(const GrafoLista *g, int u);
int gl_grau(const GrafoLista *g, int u);
int gl_conferir(const GrafoLista *g);
int gl_converter(const GrafoMatriz *origem, GrafoLista *destino);
void gl_destruir(GrafoLista *g);
#endif

hash.c

#include "hash.h"
#include <stdio.h>
#include <stdlib.h>

struct HashNo {
    HashRegistro dado;
    struct HashNo *prox;
};

static int forma(const HashTabela *t)
{
    return t != NULL && t->tamanho <= HASH_MAX_NOS;
}

static int chave_valida(int chave)
{
    return chave >= 0 && chave <= 99;
}

static size_t indice(int chave)
{
    return (size_t)(chave % HASH_BUCKETS);
}

static int dado_valido(HashRegistro d)
{
    if (!chave_valida(d.chave) || d.quantidade < 0 || d.quantidade > 100) {
        return 0;
    }
    for (size_t i = 0; i < sizeof d.nome; i++) {
        if (d.nome[i] == '\0') {
            return i > 0;
        }
        if (d.nome[i] < ' ' || d.nome[i] > '~') {
            return 0;
        }
    }
    return 0;
}

void hash_iniciar(HashTabela *t)
{
    if (t == NULL) {
        return;
    }
    for (size_t i = 0; i < HASH_BUCKETS; i++) {
        t->buckets[i] = NULL;
    }
    t->tamanho = 0;
}

int hash_inserir(HashTabela *t, HashRegistro dado, size_t *comparacoes)
{
    HashNo **ligacao;
    HashNo *novo;
    if (!forma(t) || comparacoes == NULL || !dado_valido(dado)) {
        return HASH_INVALIDO;
    }
    *comparacoes = 0;
    ligacao = &t->buckets[indice(dado.chave)];
    while (*ligacao != NULL) {
        (*comparacoes)++;
        if ((*ligacao)->dado.chave == dado.chave) {
            return HASH_DUPLICADO;
        }
        ligacao = &(*ligacao)->prox;
    }
    if (t->tamanho == HASH_MAX_NOS) {
        return HASH_LIMITE;
    }
    novo = malloc(sizeof *novo);
    if (novo == NULL) {
        return HASH_MEMORIA;
    }
    novo->dado = dado;
    novo->prox = NULL;
    *ligacao = novo;
    t->tamanho++;
    return HASH_OK;
}

int hash_buscar(const HashTabela *t, int chave, HashRegistro *saida,
                size_t *comparacoes)
{
    const HashNo *p;
    if (!forma(t) || !chave_valida(chave) || saida == NULL ||
        comparacoes == NULL) {
        return HASH_INVALIDO;
    }
    *comparacoes = 0;
    p = t->buckets[indice(chave)];
    while (p != NULL) {
        (*comparacoes)++;
        if (p->dado.chave == chave) {
            *saida = p->dado;
            return HASH_OK;
        }
        p = p->prox;
    }
    return HASH_AUSENTE;
}

int hash_remover(HashTabela *t, int chave, HashRegistro *saida,
                 size_t *comparacoes)
{
    HashNo **ligacao;
    if (!forma(t) || !chave_valida(chave) || saida == NULL ||
        comparacoes == NULL) {
        return HASH_INVALIDO;
    }
    *comparacoes = 0;
    ligacao = &t->buckets[indice(chave)];
    while (*ligacao != NULL) {
        HashNo *p = *ligacao;
        (*comparacoes)++;
        if (p->dado.chave == chave) {
            HashRegistro original = p->dado;
            *ligacao = p->prox;
            free(p);
            t->tamanho--;
            *saida = original;
            return HASH_OK;
        }
        ligacao = &p->prox;
    }
    return HASH_AUSENTE;
}

int hash_conferir(const HashTabela *t)
{
    int vistos[100] = {0};
    size_t total = 0;
    if (!forma(t)) {
        return 0;
    }
    for (size_t i = 0; i < HASH_BUCKETS; i++) {
        const HashNo *p = t->buckets[i];
        while (p != NULL) {
            if (total >= HASH_MAX_NOS || !dado_valido(p->dado)) {
                return 0;
            }
            if (indice(p->dado.chave) != i || vistos[p->dado.chave]) {
                return 0;
            }
            vistos[p->dado.chave] = 1;
            total++;
            p = p->prox;
        }
    }
    return total == t->tamanho;
}

void hash_listar(const HashTabela *t)
{
    for (size_t i = 0; i < HASH_BUCKETS; i++) {
        const HashNo *p = t->buckets[i];
        printf("[%zu]", i);
        while (p != NULL) {
            printf(" %d:%s:%d", p->dado.chave, p->dado.nome,
                   p->dado.quantidade);
            p = p->prox;
        }
        putchar('\n');
    }
}

void hash_relatar(const HashTabela *t)
{
    size_t maior = 0;
    size_t vazios = 0;
    for (size_t i = 0; i < HASH_BUCKETS; i++) {
        size_t n = 0;
        const HashNo *p = t->buckets[i];
        while (p != NULL) {
            n++;
            p = p->prox;
        }
        if (n == 0) {
            vazios++;
        }
        if (n > maior) {
            maior = n;
        }
    }
    printf("n=%zu carga=%.1f maior=%zu vazios=%zu\n", t->tamanho,
           (double)t->tamanho / HASH_BUCKETS, maior, vazios);
}

void hash_destruir(HashTabela *t)
{
    if (t == NULL) {
        return;
    }
    for (size_t i = 0; i < HASH_BUCKETS; i++) {
        while (t->buckets[i] != NULL) {
            HashNo *p = t->buckets[i];
            t->buckets[i] = p->prox;
            free(p);
        }
    }
    t->tamanho = 0;
}

hash.h

#ifndef HASH_H
#define HASH_H
#include <stddef.h>

#define HASH_BUCKETS 5
#define HASH_MAX_NOS 16
#define HASH_OK 1
#define HASH_AUSENTE 0
#define HASH_INVALIDO (-1)
#define HASH_DUPLICADO (-2)
#define HASH_MEMORIA (-3)
#define HASH_LIMITE (-4)

typedef struct {
    int chave;
    char nome[16];
    int quantidade;
} HashRegistro;

typedef struct HashNo HashNo;
typedef struct {
    HashNo *buckets[HASH_BUCKETS];
    size_t tamanho;
} HashTabela;

void hash_iniciar(HashTabela *t);
int hash_inserir(HashTabela *t, HashRegistro dado, size_t *comparacoes);
int hash_buscar(const HashTabela *t, int chave, HashRegistro *saida,
                size_t *comparacoes);
int hash_remover(HashTabela *t, int chave, HashRegistro *saida,
                 size_t *comparacoes);
int hash_conferir(const HashTabela *t);
void hash_listar(const HashTabela *t);
void hash_relatar(const HashTabela *t);
void hash_destruir(HashTabela *t);
#endif
Editar e executar esta solução
Exemplo 1 · entrada e saída esperada

Entrada padrão

1 0
1 1
1 2
1 3
1 4
2 0 1
2 0 2
2 1 3
2 2 3
3 3
4 3
8 1 3
6
5 1
3 3
5 1
7 1
6
4 4
6
9
0

Saída esperada

Campanha pronta: simulacao, 8 slots, 8 pedidos, fila 4.
Posto A cadastrado.
Posto B cadastrado.
Posto C cadastrado.
Posto D cadastrado.
Posto E cadastrado.
Rota A-B op=2 codigo=1.
Rota A-C op=2 codigo=1.
Rota B-D op=2 codigo=1.
Rota C-D op=2 codigo=1.
Consulta: A B D; arestas=2.
P1 A->D status=pendente comando=1 plano: A B D
Rota B-D op=8 codigo=1.
Recusa P1: B-D indisponivel; comando mantido.
P1 A->D status=pendente comando=1 plano: A B D
Consulta: A C D; arestas=2.
P1 A->D status=pendente comando=1 plano: A B D
Replanejado P1: A C D
Executado P1: A C D
P2 A->E status=pendente comando=1 plano: sem-plano
Recusa P2: sem plano; comando mantido.
Postos: A B C D E
Fila: 2
P1 A->D status=feito comando=0 plano: A C D
P2 A->E status=pendente comando=1 plano: sem-plano
Saida voluntaria.
Encerramento parcial: feitos=1 pendentes=1; isolados preservados.
Sessao encerrada; donos liberados.

Estado de saída: 0.

Editar e testar o exemplo 1

Complemento web criado com IA sob direção do autor e revisto por agentes. Os programas usam os recursos disponíveis até este capítulo. A licença dos códigos e do apoio é MIT; o texto dos livros e as ilustrações mantêm direitos próprios.

Galeria