c - UVA problems 12503 gives TLE -


i trying solve 12503 problem on uva online judge. think have figured out solution, gives me tle. here problem :

you have robot standing on origin of x axis. robot given instructions. task predict position after executing instructions.

• left: move 1 unit left (decrease p 1, p position of robot before moving)

• right: move 1 unit right (increase p 1)

• same i: perform same action in i-th instruction. guaranteed positive

input integer not greater number of instructions before this. first line contains number of test cases t (t <= 100). each test case begins integer n (1 <= n <= 100), number of instructions. each of following n lines contains instruction.

output

for each test case, print final position of robot. note after processing each test case, robot should reset origin.

sample input

2

3

left

right

same 2

5

left

same 1

same 2

same 1

same 4

sample output

1

-5

here code in c:

#include <stdio.h>  char com[102][20]; int command(char comd[], int pos);  int main() {     int t;     int pos;     int i, n;     char tmp[20];      scanf("%d", &t);     for(i = 0; < t; i++) {         scanf("%d", &n);          int j;          pos = 0;         (j = 0; j < n; j++) {             gets(com[j]);             if (strcmp(com[j], "left") == 0)                 pos--;             else if(strcmp(com[j], "right") == 0)                 pos++;             else {                 pos = command(com[j], pos);             }         }          printf("%d\n", pos);     }      return 0; }  int command(char comd[], int pos) {     if (strcmp(comd, "left") == 0) {         pos--;         return pos;     }     else if (strcmp(comd, "right") == 0) {         pos++;         return pos;     }     else{         int = atoi(&comd[8]);          return command(com[a-1], pos);     } } 

is there suggestion why code gives tle ?

in int command(char comd[], int pos) function, using recursive call @ last line. may lead tle.

to solve problem can use array store number of steps taken robot @ command. have access index of array later step @ previous command.

here how it-

#include <stdio.h> #include <string.h>  int move[110]; int getmove(char inp[], int);  int main() {     int t, n;     char inp[50];      scanf(" %d ",&t);     while(t--)     {         scanf(" %d ",&n);          int i, pos = 0;         for(i = 0; < n; i++)         {             gets(inp);             pos += getmove(inp, i);         }          printf("%d\n",pos);     }      return 0; }  int getmove(char inp[], int i) {     if(inp[0]=='s')     {         int j;         sscanf(strrchr(inp,' ')," %d",&j);         move[i] = move[j - 1];     }     else     {         move[i] = (inp[0] == 'l') ? -1 : 1;     }     return move[i]; } 

Comments

Popular posts from this blog

PHP DOM loadHTML() method unusual warning -

python - How to create jsonb index using GIN on SQLAlchemy? -

c# - TransactionScope not rolling back although no complete() is called -