94 lines
2.0 KiB
C++
94 lines
2.0 KiB
C++
#include <iostream>
|
|
#include <string>
|
|
#include <set>
|
|
#include <utility>
|
|
|
|
using namespace std;
|
|
|
|
struct Rope
|
|
{
|
|
Rope(pair<int, int> head, pair<int, int> tail) : head{head}, tail{tail} {}
|
|
pair<int, int> head, tail;
|
|
|
|
};
|
|
|
|
Rope move_rope(Rope rope, int dx, int dy);
|
|
|
|
int main(int argc, char* argv[])
|
|
{
|
|
Rope rope({0,0}, {0,0});
|
|
set<pair<int, int>> visited;
|
|
|
|
string line;
|
|
while(getline(cin, line))
|
|
{
|
|
char dir = line[0];
|
|
int amount = stoi(line.substr(2));
|
|
int dx = (dir=='R')?1:((dir=='L')?-1:0);
|
|
int dy = (dir=='U')?1:((dir=='D')?-1:0);
|
|
|
|
for(int i = 0; i < amount; i++)
|
|
{
|
|
rope = move_rope(rope, dx, dy);
|
|
visited.insert(rope.tail);
|
|
}
|
|
}
|
|
|
|
cout << visited.size() << endl;
|
|
}
|
|
|
|
Rope move_rope(Rope rope, int dx, int dy)
|
|
{
|
|
rope.head.first += dx;
|
|
rope.head.second += dy;
|
|
|
|
if (rope.head.first == rope.tail.first)
|
|
{ //same x
|
|
if (rope.head.second > rope.tail.second)
|
|
{
|
|
rope.tail.second = rope.head.second-1;
|
|
}
|
|
else if (rope.head.second < rope.tail.second)
|
|
{
|
|
rope.tail.second = rope.head.second+1;
|
|
}
|
|
}
|
|
else if (rope.head.second == rope.tail.second)
|
|
{ //same y
|
|
if (rope.head.first > rope.tail.first)
|
|
{
|
|
rope.tail.first = rope.head.first-1;
|
|
}
|
|
else if (rope.head.first < rope.tail.first)
|
|
{
|
|
rope.tail.first = rope.head.first+1;
|
|
}
|
|
}
|
|
else
|
|
{ //diagonal
|
|
if (abs(rope.head.first-rope.tail.first) == 1 && abs(rope.head.second-rope.tail.second) == 1)
|
|
{
|
|
return rope;
|
|
}
|
|
|
|
if (rope.head.first-rope.tail.first > 0)
|
|
{
|
|
rope.tail.first++;
|
|
}
|
|
else
|
|
{
|
|
rope.tail.first--;
|
|
}
|
|
|
|
if (rope.head.second-rope.tail.second > 0)
|
|
{
|
|
rope.tail.second++;
|
|
}
|
|
else
|
|
{
|
|
rope.tail.second--;
|
|
}
|
|
}
|
|
|
|
return rope;
|
|
} |