Error comparing characters with strcmp

Asked

Viewed 189 times

1

In the question asks to form a pair of shoes Right and Left so I used strcmp to compare,I used 1 because the strings have to be different,but I did not have the result that the question asked.

Link to the question https://www.urionlinejudge.com.br/judge/pt/problems/view/1245

Here is my code

#include<stdio.h>
#include<stdlib.h>
#include <string.h>
int main(void)
{
  int i, teste, j, c = 0;
  while(scanf("%d", &teste) != EOF)
  {
    c = 0;
    int vet[teste];
    char nome[teste][100];
    for(i = 0; i < teste; i++)
    {
        scanf("%d %s", &vet[i], nome[i]);
    }
    for(i = 0; i < teste; i++)
    {
        for(j = 0; j < teste; j++)
        {
            if(vet[i] == vet[j])
            {
                if(strcmp(nome[i], nome[j]) == 1)
                {
                    c++;
                }
            }
        }
    }
    printf("%d\n", c);
}

}

1 answer

1

You’re going through the wrong vet vector. In your logic if there are 1 million 40 D boots and at the end there is only one 40 E boot, your result will show that there are 1 million pairs. It would be right for you to mark if a boot already has the foot found.

#include<stdio.h>
#include<stdlib.h>
#include <string.h>
int main(void)
{
  int i, teste, j, c = 0;
  while(scanf("%d", &teste) != EOF)
 {
   c = 0;
   int vet[teste];
   char nome[teste][100];
   //Criei esse vetor que marcar as botas
   int vestido[teste];
   for (i = 0 ; i < teste; i++)
   {
       vestido[i] = 0;
   }
   for(i = 0; i < teste; i++)
   {
       scanf("%d %s", &vet[i], nome[i]);
   }
   for(i = 0; i < teste; i++)
   {
       for(j = 0; j < teste ; j++)
       {
           //aqui eu verifico se a bota foi encontrada
           if(vet[i] == vet[j] && vestido[i]!=1 & vestido[j]!=1)
           {
               if(strcmp(nome[i], nome[j]) == 1)
               {
                   c++;
                   //aqui eu marco se a bota encontrada
                   vestido[i] = 1;
                   vestido[j] = 1;
               }
           }
       }
   }
  printf("%d\n", c);
 }
}

I tested and was accepted, there must be several ways to improve the code and decrease the computation.

  • The complexity of the code is in order of O(n²), but there is how to do in O(n).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.