Ciao a tutti. In questi giorni mi sto allenando per le olimpiadi risolvendo alcuni esercizi.
Mi sono bloccato sull’esercizio Robot Programmabile. Riesco ad ottenere solo 40/100 a causa dell’errore:
Execution killed with signal 11 (could be triggered by violating memory limits)
Vorrei sapere come posso ottimizzare il mio codice perchè sono giorni che non ne esco fuori.
#include <stdio.h>
#include <assert.h>
#include <vector>
#define MAXN 1000000
#define MAXM 100000
enum Direction {UP, DOWN, LEFT, RIGHT};
struct Robot
{
int x, y;
Direction direction;
};
typedef struct{
int x, y;
} point;
point passeggia(int N, int M, char P[], int S[], int E[]) {
std::vector<char>command;
Robot robot;
robot.x = 0;
robot.y = 0;
robot.direction = RIGHT;
for (int i = 0; i < M; i++)
{
for (int j = S[i]; j <= E[i]; j++)
{
command.push_back(P[j]);
}
}
for (int i = 0; i < command.size(); i++)
{
if (command[i] == 'X')
break;
switch(command[i])
{
case 'R':
switch (robot.direction)
{
case LEFT:
robot.direction = UP;
break;
case RIGHT:
robot.direction = DOWN;
break;
case UP:
robot.direction = RIGHT;
break;
case DOWN:
robot.direction = LEFT;
break;
}
break;
case 'L':
switch (robot.direction)
{
case LEFT:
robot.direction = DOWN;
break;
case RIGHT:
robot.direction = UP;
break;
case UP:
robot.direction = LEFT;
break;
case DOWN:
robot.direction = RIGHT;
break;
}
break;
case 'F':
switch (robot.direction)
{
case LEFT:
robot.x--;
break;
case RIGHT:
robot.x++;
break;
case UP:
robot.y++;
break;
case DOWN:
robot.y--;
break;
}
break;
case 'B':
switch (robot.direction)
{
case LEFT:
robot.x++;
break;
case RIGHT:
robot.x--;
break;
case UP:
robot.y--;
break;
case DOWN:
robot.y++;
break;
}
break;
}
}
point p;
p.x = robot.x;
p.y = robot.y;
command.clear();
return p;
}
char P[MAXN+2];
int S[MAXM], E[MAXM];
int main() {
FILE *fr, *fw;
int N, M, i;
fr = fopen("input.txt", "r");
fw = fopen("output.txt", "w");
assert(2 == fscanf(fr, "%d %d\n", &N, &M));
assert(1 == fscanf(fr, "%s", P));
for(i=0; i<M; i++)
assert(2 == fscanf(fr, "%d %d", &S[i], &E[i]));
point p = passeggia(N, M, P, S, E);
fprintf(fw, "%d %d\n", p.x, p.y);
fclose(fr);
fclose(fw);
return 0;
}
Vi lascio il link del repository Github dove è presente il programma: