Atcoder ABC contest 335
C - Loong Tracking
Time Limit: 2 sec / Memory Limit: 1024 MiB
Score : 300 points
Problem Statement
Takahashi has created a game where the player controls a dragon on a coordinate plane.
The dragon consists of N parts numbered 1 to N, with part 1 being called the head.
Initially, part i is located at the coordinates (i,0). Process Q queries as follows.
1 C: Move the head by 1 in direction C. Here, C is one of R, L, U, and D, which represent the positive x-direction, negative x-direction, positive y-direction, and negative y-direction, respectively. Each part other than the head moves to follow the part in front of it. That is, part i (2≤i≤N) moves to the coordinates where part i−1 was before the move.
2 p: Find the coordinates of part p.
Constraints
2≤N≤1000000
1≤Q≤2×100000
For the first type of query, C is one of R, L, U, and D.
For the second type of query, 1≤p≤N.
All numerical input values are integers.
Input
The input is given from Standard Input in the following format:
N Q
query 1
⋮
query Q
Each query is in one of the following two formats:
1 C
2 p
Output
Print q lines, where q is the number of queries of the second type.
The i-th line should contain x and y separated by a space, where (x,y) are the answer to the i-th such query.
分析:
此题就是通过队列来模拟移动轨迹。
如同一条贪吃蛇在移动一般。
解答:
用Ruby自带的在数组头部插入数据的API结合面向对象的思维来解就是这么优雅。
class Snake
def initialize(n)
@num = (1..n).to_a.map {|i| [i,0]}
@d = {"U" => [0,1],"D" => [0,-1],"R" => [1,0],"L" => [-1,0]}
end
def move(s)
@num.unshift([@num[0][0]+@d[s][0],@num[0][1]+@d[s][1]])
@num.pop
end
def sputs(n1)
puts @num[n1-1].join(" ")
end
end
n,q = gets.split(" ").map(&:to_i)
ss = Snake.new(n)
for i in 0...q
t = gets.split(" ")
if t[0] == "1"
ss.move(t[1])
else
ss.sputs(t[1].to_i)
end
end