void retirarUltimaOcorrencia(struct fila *fl, int x){

    struct fila faux;
    inicializa(&faux);
    int eaux;
    int contador = 0;
    int posicao = -1;

    while(!vazia(fl))
    {
        eaux = retira(fl);
        if(eaux == x)
            posicao = contador;
        insere(&faux, eaux);
        contador++;
    }

    printf("\nPosicao: %d", posicao);

    contador = 0;
    while(!vazia(&faux))
    {
        eaux = retira(&faux);

        if(contador != posicao)
            insere(fl, eaux);

        contador++;
    }
}
void intercala(struct fila *fl1, struct fila *fl2, struct fila *fl3){
    while(!vazia(fl1) || !vazia(fl2))
    {
        if(!vazia(fl1))
            insere(fl3, retira(fl1));
        if(!vazia(fl2))
            insere(fl3, retira(fl2));
    }
}
void retirarElementos(struct fila *fl, int x){
    struct fila faux;
    inicializa(&faux);
    int eaux;

    while(!vazia(fl))
    {
        eaux = retira(fl);
        if(eaux != x)
            insere(&faux, eaux);
    }

    while(!vazia(&faux))
        insere(fl, retira(&faux));
};
예제 #4
0
int main() {
	li *l = (li*) malloc(sizeof(li));
	cab *cabecalho = (cab*) malloc(sizeof(cab));	
	char opcao;
	int num;

	cabecalho -> inilist = NULL;
	cabecalho -> fimlist = NULL;
	cabecalho -> nelem = 0;
	
	do {
		__fpurge(stdin);
		opcao = getchar();	
		
		if(opcao == 'I') {
			scanf("%d", &num);
			insere(cabecalho, num);
			imprime(cabecalho);
		}
		else if(opcao == 'R') {
			if(cabecalho -> nelem == 0)
				printf("Lista Vazia\n");
			else {
				retira(cabecalho);
				imprime(cabecalho);
			}
		}	
	} while(opcao != 'F');

return 0;
}
예제 #5
0
/* funcao para processar a devolucao de um livro */
void devolver(Requisit requisit,Livro livros,Utente utentes)
{
    Requisit aux_r;
    Utente aux_u;
    int utente_code;

    if((aux_u=valida_u(utentes)))
    {
        utente_code = aux_u->registo.cod_utente;
        if(!(historial_u(requisit,livros,utente_code,1)))
            printf("O utente nao possui livros requisitados!\n\n\n");

        else if((aux_r = valida_r(requisit)))
        {
            if((utente_code=retira(&aux_r->info.reserva)))
            {
                aux_r->info.cod_utente = utente_code;
                data_actual(&aux_r->info.data_r);
                printf("Este livro foi devolvido com sucesso e automaticamente requisitado \npelo utente com o codigo n. %d, que se encontrava em lista de espera.\n\n\n",utente_code);
            }

            else
            {
                elimina_lista_r(requisit,aux_r->info.cod_livro);
                printf("O livro foi devolvido com sucesso!\n\n\n");
            }

            gravar_fich(requisit,0);
            printf("\n\nInformacao guardada em disco.\n\n\n");
        }
    }
    else printf("Esse utente nao existe!\n\n\n");
}
예제 #6
0
파일: ListaEnc.hpp 프로젝트: caiopo/INE5408
	/**
	 * @brief      Retira o dado na posição pos e o retorna
	 *
	 * @param[in]  pos   Posição para retirar
	 *
	 * @return     O dado retirado
	 */
	T retiraDaPosicao(int pos) {
		if(pos >= size || pos < 0)
			throw std::runtime_error("posicao must be smaller than "
									"ultimo+1 and greater than zero");

		if (listaVazia())
			throw std::runtime_error("lista vazia");


		if (pos == 0)
			return retiraDoInicio();

		if (pos == size)
			return retira();

		auto e = head;

		for (int i = 0; i < pos-1; ++i)
			e = e->getProximo();

		T dado = e->getProximo()->getInfo();

		e->setProximo(e->getProximo()->getProximo());

		--size;

		return dado;
	}
예제 #7
0
파일: main.c 프로젝트: jvalv/escalonador
void opcao(node *PRONTOS,node *EXECUTANDO, node *BLOQUEADO,node *FINALIZADOS,int op){
	node *tmp;
	switch(op){
		case 0:
			libera(PRONTOS);
			break;
		case 1:
			libera(PRONTOS);
			inicia(PRONTOS);
			break;
		case 2:
			listaProcessos(PRONTOS,EXECUTANDO, BLOQUEADO, FINALIZADOS);
			break;
		case 3:
			insere(PRONTOS);
			break;
		case 9: Escalonador_Simples(PRONTOS,EXECUTANDO, BLOQUEADO,FINALIZADOS);
			break;
		case 4:
			tmp= retira(PRONTOS);
			if(tmp != NULL){
				printf("Retirado: %3d\n\n", tmp->num);
				libera(tmp);
			}
			break;
		default:
			printf("Comando invalido\n\n");
	}
}
main(){

    struct fila f1;
    inicializa(&f1);

    insere(&f1, 3);
    insere(&f1, 5);
    insere(&f1, 6);

    struct fila f2;
    inicializa(&f2);

    insere(&f2, 1);
    insere(&f2, 2);
    insere(&f2, 4);
    insere(&f2, 7);
    insere(&f2, 11);


    struct fila f3;
    inicializa(&f3);

    junta(&f1, &f2, &f3);

    while(!vazia(&f3))
        printf("\n%d", retira(&f3));

    getchar();
};
예제 #9
0
파일: main.c 프로젝트: pedropaulovc/UFSC
/**
 NOME DA FUNÇÃO: retirarContato
 ALUNOS: Pedro Paulo e Felipe dos Santos
 PROPÓSITO:
	É responsável por gerenciar as operações de remoção de contatos e delegá-las apropriadamente à lista e
	informar se tudo aconteceu de maneira correta.

 PARÂMETROS:
 nenhum

 VALOR DE RETORNO:
 nenhum

 CHAMA: exibeMenuSecundario, retira, retiraDoInicio, retiraDaPosicao, exibirMensagemErro

 CHAMADA DE: main
 */
void retirarContato() {
	int opcao, posicao, resultado;

	exibeMenuSecundario("Remover do");
	scanf("%d", &opcao);

	switch (opcao) {
	case 0:
		resultado = retira();
		break;
	case 1:
		resultado = retiraDoInicio();
		break;
	case 2:
		puts("Forneça a posição a ser removida");
		scanf("%d", &posicao);
		resultado = retiraDaPosicao(posicao);
		break;
	default:
		puts("Opção Inválida");
		break;
	}

	if (resultado != 0)
		exibirMensagemErro(resultado);
}
예제 #10
0
파일: MATRIZ.C 프로젝트: teffyhart/inf1301
void popCoor(LIS_tppLista Tab, int x, int y) {
	
	LIS_tppLista Col;
	PtoTopo* p;

	Col = achaCoor(Tab, x, y);
	p = (PtoTopo*) LIS_ObterValor(Col);
	retira(p);

	IrInicioLista(Tab);
}
void furaFila(struct fila *fl, int x){
    struct fila faux;
    inicializa(&faux);

    if(cheia(fl))
    {
        printf("Fila cheia, impossivel furar");
        return;
    }

    while(!vazia(fl))
        insere(&faux, retira(fl));

    //for(var x = 0; x <= 2 && !vazia(&aux); x++)
       // insere(fl, retira(&aux))

    insere(fl, x);

    while(!vazia(&faux))
        insere(fl, retira(&faux));
};
예제 #12
0
int main() {
    int x, i;
    vet v;
    inicia(&v);
    for (i = 0; i < 20; i++)
        insere(&v, i);
    while(!vazio(v)) {
        retira(&v, &x);
        if (x > 10)
            printf("%d ", x);
    }
    return 0;
}
int main(){
Listaint y;
inicializa(&y);
insere(&y,1);
insere(&y,9);
insere(&y,2);
imprime(&y);
//consulta(&y,13);
retira(&y,9);
imprime(&y);
system( "PAUSE");
return 0;
}
예제 #14
0
int main()
{
  int m;
  int i, j, k;
  int conta;

  while(1)
    {
      scanf(" %d %d", &n, &m);
      if(n == m && m == 0)
	break;
      
      for(i=0; i<n; i++)
	tarefa[i].numpre = 0;
      
      for(i=0; i<m; i++){
	scanf(" %d %d", &j, &k);
	j--; k--;
	if(!acha(k, j)){
	  tarefa[k].prec[tarefa[k].numpre] = j;
	  tarefa[k].numpre++;
	}
      }
      
      conta = 0;
      while(conta < n){
	for(i=0; i<n; i++)
	  if(tarefa[i].numpre == 0){
	    ordem[conta] = i;
	    retira(i);
	    conta++;
	    break;
	  }
	if(i == n){
	  /*printf("Nao eh possivel executar\n");*/
	  break;
	}
      }
      if(conta < n)
	continue;

      printf("%d", (*ordem)+1);
      for(i=1; i<n; i++)
	printf(" %d", ordem[i]+1);
      putchar('\n');
    }
  return 0;
}
예제 #15
0
	/**
	 * @brief      Retira dado de uma posição espesifica
	 *
	 * @param[in]  pos	Posição do dado que vai ser removido
	 *
	 * @return     Dado que foi removido
	 */
	T retiraDaPosicao(int pos) {
		++pos;
		if (listaVazia()) throw 20;
		if (pos < 0 || pos > size) throw 20;
		if (pos == 0) return retiraDoInicio();
		if (pos == size) return retira();
		auto current = head;
		auto old = current;
		while (--pos) {
			old = current;
			current = current->getProximo();
		}
		T retorno = current->getInfo();
		old->setProximo(current->getProximo());
		--size;
		return retorno;
	}
예제 #16
0
void * consumidor (void * args) {
  int item;

  while (1) {
    sem_wait(&semCheio);

    sem_wait(&mutex);
    item = retira();
    printf("item retirado: %d\n", item);
    printBuffer();
    sem_post(&mutex);

    sem_post(&semVazio);
  }

  pthread_exit(NULL);
}
main(){

    struct fila fl;
    inicializa(&fl);

    insere(&fl, 2);
    insere(&fl, 3);
    insere(&fl, 2);
    insere(&fl, 4);
    insere(&fl, 6);
    insere(&fl, 2);
    insere(&fl, 5);

    retirarUltimaOcorrencia(&fl, 2);

    while(!vazia(&fl))
        printf("\n%d", retira(&fl));

    getchar();
};
예제 #18
0
int main(int argc, char** argv) {
    float p1,p2,p3;
    char turma[1],matricula[8],nome[81];
    int r;
    l = inicializa();
    do{
        getchar();
        printf("\nDigite os dados do aluno:\n\n");
        printf("Nome: ");
        gets(nome);
        printf("Matricula: ");
        scanf("%s",matricula);
        printf("Turma: ");
        scanf("%c",&turma);
        getchar();
        printf("Prova 1: ");
        scanf("%f",&p1);
        getchar();
        printf("Prova 2: ");
        scanf("%f",&p2);
        getchar();
        printf("Prova 3: ");
        scanf("%f",&p3);
        l = insere_ord(l, nome, matricula, turma, p1, p2, p3);
        printf("\n\nDeseja inserir mais elementos: 1 - Sim 0 - Nao ");
        scanf("%d",&r);
    }while(r == 1);
    
    do{
      printf("\nDigite os dados do aluno a ser REMOVIDO:\n\n");
      printf("Digite a matricula: ");
      scanf("%s",matricula);
      l = retira(l, matricula);
      printf("\n\nDeseja excluir mais elementos: 1 - Sim 0 - Nao ");
      scanf("%d",&r);
    }while(r == 1);
    imprimir(l);
    
    return (EXIT_SUCCESS);
}
예제 #19
0
파일: main.c 프로젝트: jvalv/escalonador
int transfereEntre(node *origem, node*destino, node *pilhaOrigem) {
	node *novo=(node *) malloc(sizeof(node));
	novo->pid = origem->pid;
	strcpy(novo->nome,origem->nome);
	novo->io = origem->io;
	novo->io_feitos = origem->io_feitos;
	novo->cpu_feitos = origem->cpu_feitos;
	novo->cpu = origem->cpu;
	novo->prioridade = origem->prioridade;	
	novo->situacao = origem->situacao;	
	novo->prox = NULL;
	if(vazia(destino))
	destino->prox=novo;
	else{
		node *tmp = destino->prox;
		while(tmp->prox != NULL)
			tmp = tmp->prox;
		tmp->prox = novo;
	}
	retira(pilhaOrigem);
	return novo;
}
예제 #20
0
파일: largura.c 프로젝트: junin17/C
void bfs(grafo *g,int s,Fila *f){
    int u,i;
    g->cor[s]=cinza;
    g->dist[s]=0;
    esvazia(f);
    insere(f,s);

    while(!vazia(f)){
       u=retira(f);
       for(i=0;i<g->tam;i++){
            if(g->A[u][i]!=0 && g->cor[i]==branco){
                g->cor[i]=cinza;
                g->dist[i]=g->dist[u]+1;
                g->pred[i]=u;
                insere(f,i);
            }
       }

       g->cor[u]=preto;

    }

}
예제 #21
0
/*
 * Escopo principal do programa
 */
int main(void){
    ArvoreInt a;
    int x;
    char opcao[14];
    inicializa(&a);

    do{
        x = 0;
        scanf(" %[^\n]s", opcao);
        if((opcao[0] != 'l') && (opcao[0] != 'p'))
            stringParaInt(opcao, &x);
        switch(opcao[0]){
            case 'i':insere(&a, x); break;                              /* Insere Chave */
            case 'c':consultarChave(&a, x); break;                      /* Consulta Chave */
            case 'r':retira(&a, x); break;                              /* Remove Chave */
            case 'p':listarTodasChavesEmOrdem(&a, opcao[2]); break;     /* Lista todas as chaves dos nós da árvore */
            case 'n':listarChavesDoNivel(a, 1, x); break;               /* Lista chaves de um determinado nível da árvore */
            case 'd':imprimirArvore(a); break;                          /* Imprime a árvore */
        }
    }while(opcao[0] != 'e');

    return 0;
}
예제 #22
0
int preenche(int i, int j, int k)
{
  int l, t;

  ini = fim = 0;
  insere(i,j);

  t = 0;
  comp[i][j] = k;
  while(!vazia()){
    retira(&i, &j);
    t++;

    /*fprintf(stderr, "Visitei %d %d\n", i, j);*/
    l = castelo[i][j];
    if(l % 2 == 0 && comp[i][j-1] == 0){
      comp[i][j-1] = k;
      insere(i, j-1);
    }
    l = l >> 1;
    if(l % 2 == 0 && comp[i-1][j] == 0){
      comp[i-1][j] = k;
      insere(i-1, j);
    }
    l = l >> 1;
    if(l % 2 == 0 && comp[i][j+1] == 0){
      comp[i][j+1] = k;
      insere(i, j+1);
    }
    l = l >> 1;
    if(l % 2 == 0 && comp[i+1][j] == 0){
      comp[i+1][j] = k;
      insere(i+1, j);
    }
  }
  return t;
}
예제 #23
0
int main()
{
    Lista*lst = inicializada();          //Inicializa NULL
    Lista*end1 = inicializada();         //Inicializa NULL
    int  valor_digitado, valor_retira,n;

    lst=insere_ordenado(lst,18);     //Insere em ordem os valores
    imprime(lst);                    //imprime o valor
    lst=insere_ordenado(lst,90);
    imprime(lst);
    lst=insere_ordenado(lst,47);
    imprime(lst);

    printf("Digite uma numero:");
    scanf("%d",&n);
    lst=insere_ordenado(lst, n);
    imprime(lst);

    printf("Entre com um numero para busca: \n");
    scanf("%d",&valor_digitado);
    end1 = busca(lst,valor_digitado);                  // Busca endereço do  numero digitado
    if(end1 != NULL)
        printf("O valor se encontra no endereço %p.\n",end1);
    else
        printf("Numero nao encontrado.\n");

    printf("Entre com o numero para retirar: ");
    scanf("%d",&valor_retira);
    retira(lst,valor_retira);                          // Retira o numero digitado
    imprime(lst);

    libera(lst);                             // libera a lista
    lst=NULL;                                // igual lista à NULL
    imprime(lst);

    return 0;
}
예제 #24
0
파일: cadastro.cpp 프로젝트: eliseu85/c
int main (void)
{   	
    Lista* l = NULL;             /* Cria uma lista vazia */   
    int opcao = 0;    
    
    while(opcao!=9)
    {
		opcao = MenuPrincipal();
    	if(opcao==1)
    	{
    		l = insere(l);
    	}
    	else if(opcao==2)
    	{
    		imprime(l);
    	}
    	else if(opcao == 3)
    	{
    		l = retira(l);
    	}
    }

    getch();
}
void junta(struct fila *fl1, struct fila *fl2, struct fila *fl3){

    int vlr1;
    int vlr2;
    int flagUltimo;

    vlr1 = retira(fl1);
    vlr2 = retira(fl2);

    while(1)
    {
        if(vlr2 < vlr1)
        {
            insere(fl3, vlr2);
            flagUltimo = 2;
            if(vazia(fl2))
                break;
            vlr2 = retira(fl2);
        }
        else
        {
            insere(fl3, vlr1);
            flagUltimo = 1;
            if(vazia(fl1))
                break;
            vlr1 = retira(fl1);
        }
    }

    if(flagUltimo == 2)
    {
        insere(fl3, vlr1);
        while(!vazia(fl1))
            insere(fl3, retira(fl1));
    }
    else
    {
        insere(fl3, vlr2);
        while(!vazia(fl2))
            insere(fl3, retira(fl2));
    }
}
예제 #26
0
int main()
{
  int n, p, c;
  int i, j, k, d;
  int infi = 200000;
  No *temp;
  int min;

  FILE *fin = fopen("butter.in", "r");
  FILE *fout = fopen("butter.out", "w");
  
  fscanf(fin, " %d %d %d", &n, &p, &c);

  for(i=0; i<n; i++){
    fscanf(fin, " %d", &j);
    nocows[--j]++;
  }

  for(i=0; i < p; i++)
    al[i].prox = NULL;
  

  for(k = 0; k < c; k++){
    fscanf(fin, " %d %d %d", &i, &j, &d);
    i--; j--;
    temp = (No *)malloc(sizeof(No));
    temp->vert = j;
    temp->peso = d;
    temp->prox = al[i].prox;
    al[i].prox = temp;

    temp = (No *)malloc(sizeof(No));
    temp->vert = i;
    temp->peso = d;
    temp->prox = al[j].prox;
    al[j].prox = temp;
  }

  for(i=0; i<p; i++)
    for(j=0; j<p; j++)
      dist[i][j] = infi;

  /*
  for(i=0; i<p; i++){
    printf("%d: ", i);
    for(temp = al[i].prox; temp != NULL; temp = temp->prox)
      printf("%d ", temp->vert);
    printf("\n");
  }
  */

  for(k = 0; k < p; k++){
    if(nocows[k] == 0)
      continue;

    for(i = 0; i < p; i++)
      pos[i] = -1;

    dist[k][k] = 0;
    tam = 0;
    insere(k, k);

    while(tam > 0){
      i = retira(k);
      /*
      for(j=0; j<tam; j++)
	if(dist[k][HEAP[j]] < dist[k][i])
	  fprintf(stderr, "Opaaaaa!\n");
      */
      /*
      if(dist[k][i] == infi){
	fprintf(stderr, "Opaaaaaa!\n");
	break;
      }
      */
      for(temp = al[i].prox; temp != NULL; temp = temp->prox){
	j = temp->vert;
	if(dist[k][j] > dist[k][i] + temp->peso){
	  dist[k][j] = dist[k][i] + temp->peso;
	  if(pos[j] == -1)
	    insere(j, k);
	  else
	    atualiza(pos[j], k);
	}
      }
    }
  }
  /*
  for(i=0; i<p; i++)
    if(nocows[i] > 0)
      printf("Pasto %d: %d vacas\n", i, nocows[i]);
  */

  /*
  for(i=0; i<p; i++){
    if(nocows[i] == 0)
      continue;
    printf("%d: ", i);
    for(j=0; j<p; j++)
      printf("%3d ", dist[i][j]);
    printf("\n");
  }
  */
  min = calcula(0, p);
  /*printf("Pasto %d: %d\n", 0, min);*/
  for(i=1; i<p; i++){
    d = calcula(i, p);
    /*printf("Pasto %d: %d\n", i, d);*/
    if(d < min)
      min = d;
  }
  fprintf(fout, "%d\n", min);
  return 0;
}
예제 #27
0
/* funcao para cancelar uma reserva de um livro na fila de espera */
void cancelar_reserva(Requisit requisit,Livro livros,Utente utentes)
{
    int utente_code,sucesso=0,possui=1;
    Requisit aux_r;
    Utente aux_u;
    f_espera aux_fila,ant;

    if((aux_u = valida_u(utentes)))
    {
        utente_code = aux_u->registo.cod_utente;

        if(!(historial_u(requisit,livros,utente_code,2)))
        {
            printf("O utente nao possui reservas!\n\n\n");
            possui=0;
        }


        else if((aux_r=valida_r(requisit)))
        {
            aux_fila = aux_r->info.reserva.primeiro;
            while(aux_fila)
            {
                if(aux_fila->cod_utente==utente_code)
                {
                    if(aux_fila==aux_r->info.reserva.primeiro) /* caso o elemento a retirar estiver em primeiro */
                    {
                        retira(&aux_r->info.reserva);
                        sucesso=1;
                        break;
                    }
                                                                /* caso o elemento a retirar esteja em ultimo */
                    else if(aux_fila == aux_r->info.reserva.ultimo)
                    {
                        aux_r->info.reserva.ultimo = ant;
                        free(aux_fila);
                        sucesso=1;
                        break;

                    }

                    else            /* caso o elemento a retirar nao esteja em primeiro nem ultimo */
                    {
                        ant->prox = aux_fila->prox;
                        free(aux_fila);
                        sucesso=1;
                        break;
                    }
                }
                ant = aux_fila;
                aux_fila = aux_fila->prox;
            }
        }
        if(sucesso==1)
        {
            printf("Reserva cancelada com sucesso!\n\n\n");
            gravar_fich(requisit,0);
            printf("\n\nInformacao guardada em disco.\n\n\n");
        }
        else if(possui)
            printf("O codigo do livro introduzido nao esta reservado pelo utente!\n\n\n");
    }
    else printf("Esse utente nao existe!\n\n\n");
}
예제 #28
0
파일: helper_sock.c 프로젝트: trosa/filos
void limpaFila(fila *f)
{
	int maiores[NUM_PROCS];
	int p, menor=99999;
	
	imprimeFila(f);
	
	for (p=0; p<NUM_PROCS; p++){
	  maiores[p] = 0;
	}
	
	//ponteiro que irá percorrer a lista
	nodo *no;
	no = malloc(sizeof(nodo));
	no = f->inicio;
	
	inf *lixo;
	lixo = malloc(sizeof(inf));
	
	//Preencho o vetor com os maiores timestamps de cada filosofo
	while(no != NULL){
	printf("Estou verificando a seguinte requisicao: %d %d %d %d\n", no->info->garfo, no->info->idf, no->info->msg, no->info->rel);
	  if (no->info->rel > maiores[no->info->idf]){
	    maiores[no->info->idf] = no->info->rel;
	  }
	  no = no->prox;
	  printf("MAIORES: ");
	  for (p=0; p<NUM_PROCS; p++)
	    if (maiores[p] != 0)
	      printf("%d ", maiores[p]);
	  printf("\n");
	}

	//Encontro o menor timestamp entre os maiores valores dos filosofos
 	for (p=0; p<NUM_PROCS; p++){
	  if (maiores[p] != 0)
	    if (menor > maiores[p])
	      menor = maiores[p];
 	}
 	printf("MENOR: %d\n", menor);
	
	
	//Percorro a fila retirando 
	no = f->inicio;

//REMOVER ISSO

	FILE *fg;

		if ((fg = fopen(GO_FILE,"w")) == NULL) {
			perror("fopen nao deu");
		}

		char goBuf[100];
		sprintf(goBuf,"%d",relogio);
		
		fputs(goBuf, fg);

	fclose(fg);

//REMOVER ISSO!
	
		while(no != NULL){
	  if (no->info->rel < menor){
// 	    printf("NO: %d %d %d\n", no->info->idf, no->info->msg, no->info->rel);
	    if (no->info->msg == VOP){
	      lixo = retira(f);
 	      printf("Estou retirando: %d %d %d %d\n", lixo->garfo, lixo->idf, lixo->msg, lixo->rel);
	      sem[lixo->garfo]++;

				int h;
				printf("garfos: ");
				for(h=0;h<NUM_PROCS;h++) {
					printf("%d ", sem[h]);
	    	}
				printf("\n");
			}
	    else if (no->info->msg == POP){
	      if (sem[no->info->garfo]>0){
				lixo = retira(f);
 				printf("Estou retirando: %d %d %d %d\n", lixo->garfo, lixo->idf, lixo->msg, lixo->rel);
				sem[lixo->garfo]--;

				int h;
				printf("garfos: ");
				for(h=0;h<NUM_PROCS;h++) {
					printf("%d ", sem[h]);
	    	}
				printf("\n");

				FILE *fg;

				if ((fg = fopen(GO_FILE,"w")) == NULL) {
					perror("fopen nao deu");
				}
				
				char goBuf[100];
				sprintf(goBuf,"%d",relogio);
				fputs(goBuf, fg);

				fclose(fg);

	      }
	    }
	  }
	  no = no->prox;
	}

	free(no);
	free(lixo);
}	
int main() {
  //inicialização
  camera *cam = camera_inicializa(0);
  if(!cam)
    erro("erro na inicializacao da camera\n");

  int largura = cam->largura;
  int altura = cam->altura;

  if(!al_init())
    erro("erro na inicializacao do allegro\n");

  if(!al_init_image_addon())
    erro("erro na inicializacao do adicional de imagem\n");

  if(!al_init_primitives_addon())
    erro("erro na inicializacao do adicional de primitivas\n");

  ALLEGRO_TIMER *timer = al_create_timer(1.0 / FPS);
  if(!timer)
    erro("erro na criacao do relogio\n");

  ALLEGRO_DISPLAY *display = al_create_display(largura, altura);
  if(!display)
    erro("erro na criacao da janela\n");

  ALLEGRO_EVENT_QUEUE *queue = al_create_event_queue();
  if(!queue)
    erro("erro na criacao da fila\n");

  al_register_event_source(queue, al_get_timer_event_source(timer));
  al_register_event_source(queue, al_get_display_event_source(display));

  al_start_timer(timer);

  /**********/

  unsigned char ***matriz = camera_aloca_matriz(cam);
  int ***background = alocaHsvMatriz(cam->largura, cam->altura);

  fila *f = aloca();

  //cor para desenhar o círculo
  ALLEGRO_COLOR cor = al_map_rgb_f(0, 0, 1);

  ALLEGRO_BITMAP *buffer = al_get_backbuffer(display);

  //tela exibindo img normal
  ALLEGRO_BITMAP *esquerda = al_create_sub_bitmap(buffer, 0, 0, largura, altura);

  //tela mostrando como o computador enxerga
  //ALLEGRO_BITMAP *direita = al_create_sub_bitmap(buffer, largura/2, 0, largura/2, altura/2);
  ALLEGRO_BITMAP *silhueta = al_create_bitmap(largura, altura);

  /**********/
  srand(time(NULL));
  int desenhar = 0;
  int terminar = 0;

  int cycle = 0;
  int hitx = rand() % (largura);
  int hity = rand() % (altura);

  int x, y;

  float cyr, cxr, cnr, lastCx, lastCy;

  int r, g, b, r2, g2, b2;

  int h, s, v, h2, s2, v2;
  int fh, fs, fv;

  int dh, ds, dv;
  int tempH;

  int token;

  double value;
  int dist;

  al_rest(1);

  for(y = 0; y < altura; y++)
    for(x = 0; x < largura; x++){
      rgbToHsv(cam->quadro[y][x][0], cam->quadro[y][x][1], cam->quadro[y][x][2], 
        &background[y][x][0], &background[y][x][1], &background[y][x][2]);

      if(background[y][x][0] > 180){
        background[y][x][0] -= 360;
        background[y][x][0] = -background[y][x][0];
      }
        
    }

  al_rest(1);

  for(y = 0; y < altura; y++)
    for(x = 0; x < largura; x++){
      rgbToHsv(cam->quadro[y][x][0], cam->quadro[y][x][1], cam->quadro[y][x][2], 
        &fh, &fs, &fv);

      if(fh > 180){
        fh -= 360;
        fh = -fh;
      }

      background[y][x][0] += fh;
      background[y][x][0] /=2;

      background[y][x][1] += fs;
      background[y][x][1] /=2;
      
      background[y][x][2] += fv;
      background[y][x][2] /=2;  
    }

  //gameloop
  while(1) {
    ALLEGRO_EVENT event;

    al_wait_for_event(queue, &event);

    switch(event.type) {
    case ALLEGRO_EVENT_TIMER:
      desenhar = 1;

      break;

    case ALLEGRO_EVENT_DISPLAY_CLOSE:
      terminar = 1;
      break;

    default:
      printf("evento desconhecido\n");
    }

    if(terminar)
      break;

    //interpretar img e realizar transformações
    printf("%d\n", al_is_event_queue_empty(queue));
    if(desenhar && al_is_event_queue_empty(queue)) {
      desenhar = 0;
      camera_atualiza(cam);

      /**********/

      int bx, by, bn;

      cyr = 0;
      cxr = 0;
      cnr = 0;

      for(y = 0; y < altura; y++){
        for(x = 0; x < largura; x++){
          //Espada
          r = cam->quadro[y][x][0];
          g = cam->quadro[y][x][1];
          b = cam->quadro[y][x][2];

          rgbToHsv(r, g, b, &h, &s, &v);

          if(h < 15 || h > 345)
            if(s > 75 && v > 75){
              cyr += y;
              cxr += x;
              cnr++;
            }

          //Silhueta (REFINAR!!!)
          if(h > 180)
            tempH = -(h - 360);

          else
            tempH = h;

          dh = tempH - background[y][x][0];
          if(dh < 0)
            dh = -dh;

          ds = s - background[y][x][1];
          if(ds < 0)
            ds = -ds;

          dv = v - background[y][x][2];
          if(dv < 0)
            dv = -dv;

          //dh > 15 && ds > 10 para tirar a interfencia de iluminacao, mas gera mtuiro ruido
          //ds > 25 é o mais preciso, mas sofre de interferencia de iluminacao
          if(dv > 25){
            //valores para teste!
            matriz[y][x][0] = 37;
            matriz[y][x][1] = 50;
            matriz[y][x][2] = 248;
          }

          else{
            matriz[y][x][0] = 0;
            matriz[y][x][1] = 0;
            matriz[y][x][2] = 0;
          }

          //Escudo
          if(h < 135 && h > 105 && s > 50 && v > 75){
            by += y;
            bx += x;
            bn++;

            matriz[y][x][0] = 0;
            matriz[y][x][1] = 255;
            matriz[y][x][2] = 0;
          }
        }
      }

     /*for(y = 1; y < altura-1; y++)
        for(x = 1; x < largura-1; x++){
          token = 4;

          if(255 != matriz[y+1][x][0])
            token--;
          if(255 != matriz[y-1][x][0])
            token--;
          if(255 != matriz[y][x+1][0])
            token--;
          if(255 != matriz[y][x-1][0])
            token--;

          if(token == 0){
            matriz[y][x][0] = 0;
            matriz[y][x][1] = 0;
            matriz[y][x][2] = 0;
          }*/

      cycle++;
      if(cycle > 50 && bn > 0){
        value = (pow(hitx - (bx / 2 /bn), 2) + pow(hity - (by / 2 / bn), 2));
        dist = sqrt(value) - 7;

        if(dist < 100 && dist > -100 && bn > 0)
          printf("block!\n");

        else{
          if(matriz[hity][hitx][0] == 255)
            printf("hit\n");

          else
            printf("miss\n");
        }

        cycle = 0;
        hitx = rand() % (largura/2);
        hity = rand() % (altura/2);
      }

      /**********/
      camera_copia(cam, cam->quadro, esquerda);

      //Copia img editada na img direita
      camera_copia(cam, matriz, silhueta);
      //cor para teste!
      al_convert_mask_to_alpha(silhueta, al_map_rgb(37, 50, 248));
      al_draw_bitmap(silhueta, 0, 0, 0);
      /**********/

      if(bn > 0)
        al_draw_circle(bx / bn, by / bn, 100, al_map_rgb(0, 0, 255), 1);

      if(cycle >= 40){
        if(cycle < 48){
          al_draw_circle(hitx, hity, 15, al_map_rgb(0, 0, 255), 30);
          al_draw_circle(hitx + largura, hity, 6, al_map_rgb(0, 0, 255), 3);
        }

        else
          al_draw_circle(hitx, hity, 15, al_map_rgb(255, 0, 0), 30);
      }

      if(cnr > 10){
        lastCx = cxr / cnr;
        lastCy = cyr / cnr;

        al_draw_circle(lastCx, lastCy, 100, al_map_rgb(255, 0, 0), 1);

        insere(f, lastCx, lastCy);
      }

      else
        insere(f, lastCx, lastCy);

      if(f->count > 10)
          retira(f);

      drawAtk(f);

      al_flip_display();
    }
  }

  /**********/

  libera(f);

  al_destroy_bitmap(silhueta);

  al_destroy_bitmap(esquerda);

  camera_libera_matriz(cam, matriz);
  liberaHsvMatriz(background, cam->largura, cam->altura);

  /**********/

  al_stop_timer(timer);

  al_unregister_event_source(queue, al_get_display_event_source(display));
  al_unregister_event_source(queue, al_get_timer_event_source(timer));

  al_destroy_event_queue(queue);
  al_destroy_display(display);
  al_destroy_timer(timer);

  al_shutdown_primitives_addon();
  al_shutdown_image_addon();
  al_uninstall_system();

  camera_finaliza(cam);

  return EXIT_SUCCESS;
}
예제 #30
0
int main()
{
  int i, j;
  int infi;
  int max;


  FILE *fin = fopen("maze1.in", "r");
  FILE *fout = fopen("maze1.out", "w");

  int w, h;

  fscanf(fin, " %d %d", &w, &h);


  infi = 10000;

  for(i=0; i<2*h+1; i++){
    for(j=0; j<2*w+1; j++){
      do{
	labirinto[i][j] = getc(fin);
      }while(labirinto[i][j] == '\n');
      dist[i][j] = infi;
    }
  }

  ini = fim = 0;

  for(i=0; i<2*h+1; i++){
    if(labirinto[i][0] == ' '){
      dist[i][1] = 1;
      insere(i, 1);
    }
    if(labirinto[i][2*w] == ' '){
      dist[i][2*w-1] = 1;
      insere(i, 2*w-1);
    }
  }

  for(j=0; j<2*w+1; j++){
    if(labirinto[0][j] == ' '){
      dist[1][j] = 1;
      insere(1, j);
    }
    if(labirinto[2*h][j] == ' '){
      dist[2*h-1][j] = 1;
      insere(2*h-1, j);
    }
  }


  while(!vazia()){
    retira(&i, &j);

    if(i < 2*h-1 && labirinto[i+1][j] == ' ' && labirinto[i+2][j] == ' '
       && dist[i][j] + 1 < dist[i+2][j])
      {
	dist[i+2][j] = dist[i][j] + 1;
	insere(i+2, j);
      }

    if(i > 1  && labirinto[i-1][j] == ' ' && labirinto[i-2][j] == ' '
       && dist[i][j] + 1 < dist[i-2][j])
      {

	dist[i-2][j] = dist[i][j] + 1;
	insere(i-2, j);
      }

    if(j < 2*w-1 && labirinto[i][j+1] == ' ' && labirinto[i][j+2] == ' '
       && dist[i][j] + 1 < dist[i][j+2])
      {

	dist[i][j+2] = dist[i][j] + 1;
	insere(i, j+2);
      }

    if(j > 1  && labirinto[i][j-1] == ' ' && labirinto[i][j-2] == ' '
       && dist[i][j] + 1 < dist[i][j-2])
      {

	dist[i][j-2] = dist[i][j] + 1;
	insere(i, j-2);
      }
  }

  max = 0;
  for(i=0; i<2*h+1; i++){
    for(j=0; j<2*w+1; j++){
      if(dist[i][j] < infi && dist[i][j] > max)
	max = dist[i][j];
    }
  }


  fprintf(fout,"%d\n", max);


  return 0;
}