Is there any way to improve the performance of this code?

Asked

Viewed 75 times

-3

I have already found the resolution of this issue and all the results are in line with what the question asks, but I think the solution is a little slow, because it is giving Time limit exceeded

Question link

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

 struct p
 {
    char presente[3][100], nome[100];
 };

 int main(int argc, char** argv)
 {
   int  i, j;
   int teste;
   char nome1[100], nome2[100];
   while(scanf("%d", &teste) != EOF)
   {
     struct p presentes[teste];

      for(i = 0; i < teste; i++)
      {
         scanf("%s", presentes[i].nome);
         for(j = 0; j < 3; j++)
         {
            scanf("%s", presentes[i].presente[j]);
         }
      }
      int achou = 0, c = 0;
      do
      {
         scanf("%s %s", nome1, nome2);
         for(i = 0, achou = 0; i < teste; i++)
         {
            for(j = 0; j < 3; j++)
            {
                if(0 == strcmp(presentes[i].nome, nome1) && (0 == strcmp(presentes[i].presente[j], nome2)))
                {
                    achou = 1;
                    c++;
                }
            }
        }
        if(achou == 1)
        {
            printf("Uhul! Seu amigo secreto vai adorar o/\n");
        }
        else
        {
            printf("Tente Novamente!\n");
        }
    }
    while(c != 3);
}
  system("pause");
  return 0;
}
  • What you can do to improve code performance is put a break; in each for when you have already found it, the way I answered your last question. If you do not solve you have to choose another algorithm/solution

1 answer

-1

First, please put the problem also to evaluate us, I suppose this problem is someone from the right URI?
But looking at your code looks like it could be improved in some ways

for(j = 0; j < 3; j++)
        {
            if(0 == strcmp(presentes[i].nome, nome1) && (0 == strcmp(presentes[i].presente[j], nome2)))
            {
                achou = 1;
                c++;
                break;
            }
        }

Using break you for execution when you find such a situation.

  • Look at the link of the question I put in the description of the problem, I did what you did I put the break, but still giving ime limit exceeded.

  • try to decrease the size of the character array, 100 can this eating too much memory unnecessary

  • I managed to solve the problem, put my solution here?

  • Yes, please!

Browser other questions tagged

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