Advertisement
Tertius

Untitled

Oct 10th, 2014
206
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.96 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. int frequencyNumber(int array[], int x, int i, int j){
  4.     int m;
  5.     int retorno = 0;
  6.     int k;
  7.  
  8.  
  9.     m = (i+j)/2;
  10.     if(j == 1 && array[m] == x){
  11.         retorno++;
  12.         m = 0;
  13.     }
  14.  
  15.     if(i < j - 1){
  16.         if(array[m] > x){
  17.             j = m;
  18.             return frequencyNumber(array, x, i, j);
  19.         }else if(array[m] < x){
  20.             i = m;
  21.             return frequencyNumber(array, x, i, j);
  22.         }else{
  23.             retorno++;
  24.             k = m - 1;
  25.             while(k >= i && array[k] == x){
  26.                 retorno++;
  27.                 k--;
  28.             }
  29.             k = m + 1;
  30.             while(k <= j && array[k] == x){
  31.  
  32.                 retorno++;
  33.                 k++;
  34.             }
  35.         }
  36.     }
  37.     return retorno;
  38. }
  39.  
  40. int main()
  41. {
  42.     int *array = NULL;
  43.     int *numero_frequencia = NULL;
  44.     int *caso_array = NULL;
  45.     int *caso_numero_frequencia = NULL;
  46.     int T;
  47.     int N = 0, Q = 0;
  48.     int i, j;
  49.     int resultado;
  50.     FILE* entrada;
  51.     FILE* saida;
  52.  
  53.     entrada = fopen("T1Q1.in.txt", "r");
  54.     saida = fopen("T1Q1.out.txt", "w");
  55.  
  56.     fscanf(entrada, "%d", &T);
  57.  
  58.     for(j = 1; j <= T; j++)
  59.     {
  60.         fscanf(entrada, "%d", &N);
  61.         fscanf(entrada, "%d", &Q);
  62.  
  63.         caso_array = (int*)realloc(array, N*sizeof(int));
  64.         caso_numero_frequencia = (int*)realloc(numero_frequencia, Q*sizeof(int));
  65.  
  66.         for(i = 0; i < N; i++){
  67.             fscanf(entrada, "%d", &caso_array[i]);
  68.         }
  69.         for(i = 0; i < Q; i++){
  70.             fscanf(entrada, "%d", &caso_numero_frequencia[i]);
  71.         }
  72.         fprintf(saida, "caso %d :\n", j);
  73.         for(i = 0; i < Q; i++){
  74.             resultado = frequencyNumber(caso_array, caso_numero_frequencia[i], 0, N - 1);
  75.             fprintf(saida, "%d\n", resultado);
  76.         }
  77.  
  78.     }
  79.     fclose(entrada);
  80.     fclose(saida);
  81.     free(caso_array);
  82.     free(caso_numero_frequencia);
  83.     return 0;
  84. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement