Advertisement
daemonio

alfa tarefa A

Mar 3rd, 2013
168
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.23 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. #define TAM_AMIGO 100
  5. #define TAM_TOTAL 200
  6.  
  7. // alfa_tarefa_a.c, versão 1.0 @ Sun Mar  3 11:14:59 BRT 2013
  8. // alfa_tarefa_a.c, versão 1.1 @ Sun Mar 10 00:06:35 BRT 2013
  9.  
  10. int soma_vetor(int *v, int len) ;
  11. void *my_malloc(int tam) ;
  12.  
  13. int soma_vetor(int *v, int len) {
  14.     int i ;
  15.     int soma=0 ;
  16.  
  17.     for(i=0; i<len; i++) soma+=v[i] ;
  18.  
  19.     return soma ;
  20. }
  21.  
  22. void *my_malloc(int tam) {
  23.     char *p ;
  24.  
  25.     p = malloc(tam * sizeof(int)) ;
  26.    
  27.     if(p == NULL) {
  28.         printf("Erro: Impossivel alocar memora.\n") ;
  29.         exit(-1) ;
  30.     }
  31.  
  32.     return p ;
  33. }
  34.  
  35. int main(void) {
  36.     int *vetor_tesouros ;
  37.     int *vetor_amigo1 ;
  38.     int *vetor_amigo2 ;
  39.     int tam_amigo1, tam_amigo2 ;
  40.    
  41.     int N, i, j, t ;
  42.  
  43.     printf("Digite o valor do bau: ") ;
  44.     scanf("%d", &N) ;
  45.  
  46.     /* Aloca memória para os vetores */
  47.     vetor_tesouros = my_malloc(N) ;
  48.     vetor_amigo1   = my_malloc(N) ;
  49.     vetor_amigo2   = my_malloc(N) ;
  50.  
  51.     /* leitura dos dados */
  52.     for(i=0; i<N; i++) {
  53.         printf("Digite o valor de numero %d: ", i+1) ;
  54.         scanf("%d", &vetor_tesouros[i]) ;
  55.     }
  56.  
  57.     /* ordenação */
  58.     for(i=0; i<N; i++) {
  59.         for(j=i+1; j<N; j++) {
  60.             if(vetor_tesouros[i]<vetor_tesouros[j]){
  61.                 t=vetor_tesouros[i];
  62.                 vetor_tesouros[i]=vetor_tesouros[j];
  63.                 vetor_tesouros[j]=t;
  64.             }
  65.         }
  66.     }
  67.  
  68.     /* distribuição dos tesouros */
  69.     vetor_amigo1[0] = vetor_tesouros[0] ; tam_amigo1 = 1 ;
  70.     vetor_amigo2[0] = vetor_tesouros[1] ; tam_amigo2 = 1 ;
  71.  
  72.     for(i=2; i<N; i++) {
  73.         /* se a soma do amigo1 for menor então coloca o elemento nele
  74.          * caso contrário coloca o elemento no amigo2. */
  75.         if(soma_vetor(vetor_amigo1, tam_amigo1) < soma_vetor(vetor_amigo2, tam_amigo2)) {
  76.             vetor_amigo1[tam_amigo1++] = vetor_tesouros[i] ;
  77.         } else {
  78.             vetor_amigo2[tam_amigo2++] = vetor_tesouros[i] ;
  79.         }
  80.     }
  81.  
  82.     /* output */
  83.     printf("output: %d\n", abs(soma_vetor(vetor_amigo1, tam_amigo1)-soma_vetor(vetor_amigo2, tam_amigo2))) ;
  84.  
  85.     free(vetor_tesouros) ;
  86.     free(vetor_amigo1) ;
  87.     free(vetor_amigo2) ;
  88.  
  89.     return 0 ;
  90.  
  91. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement