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çãoExemplo 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