' 有n個球編號0~n-1{ 3<n<5*10^5},先將n個球依順時鐘圍成一圈
' m個指令F A B 或R A B {2<m<10^3}
' F A B 代表將編號A的球移至B球的順鄰處 、 R A B 代表將編號A的球移至B球的逆鄰處
' 執行m個指令後,輸出編號0的 逆鄰 及 順鄰
參考程式:
Const MaxN As Integer = 500000 '最多 50 萬
Dim f(MaxN) As Integer
Dim r(MaxN) As Integer
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
FileOpen(1, "in1.txt", OpenMode.Input)
'FileOpen(2, "in2.txt", OpenMode.Input) '本題只 in1
FileOpen(3, "out.txt", OpenMode.Output)
For fn = 1 To 1 '本題只 in1
If fn = 2 Then PrintLine(3)
Dim t As Integer = LineInput(fn)
For k = 1 To t
Dim line As String = LineInput(fn)
Dim nm() = line.Split(" ") '依 空白 分 n m
Dim n As Integer = nm(0), m As Integer = nm(1)
For i = 1 To n - 2
f(i) = i + 1
r(i) = i - 1
Next
f(0) = 1 : f(n - 1) = 0
r(0) = n - 1 : r(n - 1) = n - 2
For j = 1 To m
line = LineInput(fn)
Dim cab() = line.Split(" ") '依 空白 分 c a b
Dim c As Char = cab(0), a As Integer = cab(1), b As Integer = cab(2)
If a = b Then Continue For
If (c = "F" And f(b) = a) Then Continue For
If (c = "R" And r(b) = a) Then Continue For
shout(a)
If c = "F" Then
shinf(a, b)
Else
shinr(a, b)
End If
Next j
PrintLine(3, r(0) & " " & f(0))
Next k
Next fn
End
End Sub
Sub shout(ByVal a As Integer) '將 a 移出
r(f(a)) = r(a)
f(r(a)) = f(a)
End Sub
Sub shinf(ByVal a As Integer, ByVal b As Integer) '將 a 移入至 b 之順鄰處
r(a) = b
f(a) = f(b)
r(f(b)) = a
f(b) = a
End Sub
Sub shinr(ByVal a As Integer, ByVal b As Integer) '將 a 移入至 b 之逆鄰處
f(a) = b
r(a) = r(b)
f(r(b)) = a
r(b) = a
End Sub
in1.txt
3
4 3
R 3 2
F 3 0
F 1 2
5 6
F 2 1
R 1 3
F 2 4
F 1 4
R 0 2
R 3 4
6 8
F 1 3
R 3 4
F 5 1
F 3 3
R 2 0
R 0 3
F 4 5
R 2 1
out.txt
1 3
1 2
4 3
3
4 3
R 3 2
F 3 0
F 1 2
5 6
F 2 1
R 1 3
F 2 4
F 1 4
R 0 2
R 3 4
6 8
F 1 3
R 3 4
F 5 1
F 3 3
R 2 0
R 0 3
F 4 5
R 2 1
1 3
1 2
4 3
0 意見:
張貼留言