[Help] Problem 4C-Time Limit Exceed/Runtime Error

Revision en2, by NeekT, 2021-02-03 20:39:55

Hi everyone, i'm trying to solve problem 4C. (https://codeforces.com/problemset/problem/4/C)

You have to build a database of usernames and modify the entry if the name is already taken. I defined a data structure to hold the username and the number of time it appears in the database. Then i asked for each username and checked for repetitions. This is my first attempt:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
#define MAX_NAME 32
 
typedef struct{
  int rep;
  char name[MAX_NAME+1];
}entry_t;
 
int main(){
  entry_t* db;
  int i,j,n;
  
  scanf("%d", &n);
  db=malloc(sizeof(entry_t)*n);/*Allocate memory for the name database*/
  if(db){
    
    for(i=0; i<n; i++)  /*Set all repetions of each entry to zero*/
      db[i].rep=0;
      
    for(i=0; i<n; i++){  /*Acquire entry and check for repetitions*/
      scanf("%s", db[i].name);
      for(j=0; j<i; j++){
        if(!strcmp(db[i].name, db[j].name))
          (db[i].rep)++;
      }                   /*Print out the results*/
      if(!(db[i].rep))
        printf("OK\n");
      else
        printf("%s%d\n", db[i].name, db[i].rep);
    }
  }else
    printf("Errore allocazione memoria");
  return 0;
}

I tried to allocate the memory using the malloc function and i got the Time Limit Exceeded error code. So i tried (mostly out of desperation) to declare a big enough array to hold all the data, this way:

typedef struct{
  int rep;
  char name[MAX_NAME+1];
}entry_t;
 
int main(){
  entry_t db[10000];

and i got a different error: Runtime Error. So i tried to go bigger

typedef struct{
  int rep;
  char name[MAX_NAME+1];
}entry_t;
 
int main(){
  entry_t db[100000];
  int i,j,n;

and i got again the Time Limit Exceed error.

Can someone give me a hint about what i'm doing wrong? Also, i'd rather not use "continue" or "break" commands since my professor doesn't want me to get in the habit of it...go figure. I've seen some accepted answers that seem to be very similar to mine except for these two commands. I've also seen some people using a hashing function, which seems a really cool thing to learn but I'd like to go for a more basic approach first. Thanks.

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en2 English NeekT 2021-02-03 20:39:55 0 (published)
en1 English NeekT 2021-02-03 20:35:47 2319 Initial revision (saved to drafts)