84 lines
2.3 KiB
C++
84 lines
2.3 KiB
C++
#include <bits/stdc++.h>
|
|
|
|
using namespace std;
|
|
|
|
using Coords = pair<int, int>;
|
|
|
|
void moveTail(const Coords& head, Coords& tail){
|
|
if(head.first - tail.first > 1){
|
|
tail.first++;
|
|
} else if(head.first - tail.first < -1){
|
|
tail.first--;
|
|
}
|
|
|
|
if(head.second - tail.second > 1){
|
|
tail.second++;
|
|
} else if(head.second - tail.second < -1){
|
|
tail.second--;
|
|
}
|
|
// if(abs(head.first - tail.first) > 1 || abs(head.second - tail.second) > 1){
|
|
// if(abs(head.first - tail.first) >= 1 && abs(head.second - tail.second) >= 1){
|
|
// if(head.first > tail.first && head.second > tail.second){
|
|
// tail.first++;
|
|
// tail.second++;
|
|
// } else if(head.first > tail.first && head.second < tail.second){
|
|
// tail.first++;
|
|
// tail.second--;
|
|
// } else if(head.first < tail.first && head.second > tail.second){
|
|
// tail.first--;
|
|
// tail.second++;
|
|
// } else{
|
|
// tail.first--;
|
|
// tail.second--;
|
|
// }
|
|
// } else if(abs(head.first - tail.first > 1)){
|
|
// if(head.first > tail.first){
|
|
// tail.first++;
|
|
// } else{
|
|
// tail.first--;
|
|
// }
|
|
// } else{
|
|
// if(head.second > tail.second){
|
|
// tail.second++;
|
|
// } else{
|
|
// tail.second--;
|
|
// }
|
|
// }
|
|
// }
|
|
}
|
|
|
|
int main(){
|
|
ifstream input_file("test.txt");
|
|
string line;
|
|
|
|
Coords head(0, 0), tail(0, 0);
|
|
set<Coords> visited_by_tail;
|
|
visited_by_tail.insert(tail);
|
|
|
|
while(getline(input_file, line)){
|
|
stringstream ss(line);
|
|
char direction;
|
|
int steps;
|
|
|
|
ss >> direction >> steps;
|
|
|
|
while(steps > 0){
|
|
if(direction == 'R'){
|
|
head.first++;
|
|
} else if(direction == 'L'){
|
|
head.first--;
|
|
} else if(direction == 'U'){
|
|
head.second++;
|
|
} else if(direction == 'D'){
|
|
head.second--;
|
|
}
|
|
moveTail(head, tail);
|
|
visited_by_tail.insert(tail);
|
|
steps--;
|
|
}
|
|
}
|
|
|
|
cout << "Number of positions visited by the tail: " << visited_by_tail.size() << endl;
|
|
|
|
return 0;
|
|
} |