The problem is simple. But I tried to submit two different codes, one of them got a WA verdict while the other one got a AC verdict. The solutions are nearly same. Just by changing the input mechanism the solution gets accepted. I can't understand what the problem is. Link to the problem is here.
Abridged Problem Statement:
You have a robot standing on the origin of x axis. The robot will be given some instructions. Your task is to predict its position after executing all the instructions.
- LEFT: move one unit left (decrease p by 1, where p is the position of the robot before moving)
- RIGHT: move one unit right (increase p by 1)
- SAME AS i: perform the same action as in the i-th instruction. It is guaranteed that i is a positive integer not greater than the number of instructions before this
Input: The first line contains the number of test cases T (T ≤ 100). Each test case begins with an integer n (1 ≤ n ≤ 100), the number of instructions. Each of the following n lines contains an instruction.
Output For each test case, print the final position of the robot.
Note that after processing each test case, the robot should be reset to the origin.
Sample Input
2
3
LEFT
RIGHT
SAME AS 2
5
LEFT
SAME AS 1
SAME AS 2
SAME AS 1
SAME AS 4
Sample Output
1
-5
Here's the code which got AC verdict:
#include <bits/stdc++.h>
using namespace std;
int TC = 0 , N = 0 , p = 0 , in = 0;
string instruction , as;
vector<string> instructions;
int main() {
cin >> TC;
while(TC--) {
cin >> N; p = 0; scanf("\n");
instructions.assign(N , "");
for(int i = 0 ; i < N ; ++i) {
cin >> instruction;
if(instruction.compare("LEFT") == 0) {
instructions[i] = instruction;
}
else if(instruction.compare("RIGHT") == 0) {
instructions[i] = instruction;
}
else { scanf("\n");
cin >> as >> in;
instructions[i] = instructions[in - 1];
}
}
for(auto x : instructions) {
if(x.compare("RIGHT") == 0) ++p;
else --p;
}
cout << p << endl;
instructions.clear();
}
return 0;
}
Here, is the code which got WA verdict:
#include <bits/stdc++.h>
using namespace std;
int TC = 0 , N = 0 , p = 0 , in = 0;
string instruction , as;
vector<string> instructions;
int main() {
cin >> TC;
while(TC--) {
cin >> N; p = 0; scanf("\n");
instructions.assign(N , "");
for(int i = 0 ; i < N ; ++i) {
getline(cin , instruction);
if(instruction.compare("LEFT") == 0) {
instructions[i] = instruction;
}
else if(instruction.compare("RIGHT") == 0) {
instructions[i] = instruction;
}
else {
instructions[i] = instructions[instruction.back() - '0' - 1]; // I think the problem is here but don't know what it is.
}
}
for(auto x : instructions) {
if(x.compare("RIGHT") == 0) ++p;
else --p;
}
cout << p << endl;
instructions.clear();
}
return 0;
}
Maybe instruction.back() is creating some problem. Please clarify my doubt.