You are n boxes in a line on the table numbered 1 ... Your task is to simulate 4
Kinds of commands:
? 1 x Y:move box X to the left and Y (ignore this if X are already the left of Y)
? 2 x Y:move box X to the right and Y (ignore this if X are already the right of Y)
? 3 x Y:swap box X and Y
? 4:reverse the whole line.
Commands is guaranteed to be valid, i.e. X would be is not equal to Y.
For example, if n = 6, after executing 1 1 4, the line becomes 2 3 1 4 5 6. Then after executing
2 3 5, the line becomes 2 1 4 5 3 6. Then after executing 3 1 6, the line becomes 2 6 4 5 3 1.
Then after executing 4, then line becomes 1 3 5 4 6 2
Input
There'll is at the most test cases. Each test case begins with a line containing 2 integers n, m
(1≤n, M≤100, 000). Each of the following m lines contain a command.
Output
for each test case, print the sum of numbers at odd-indexed positions. Positions is numbered 1 to n
From left to right.
Sample Input
6 4
1 1 4
2 3 5
3 1 6
4
6 3
1 1 4
2 3 5
3 1 6
100000 1
4
Sample Output
Case 1:12
Case 2:9
Case 3:2,500,050,000
You have a row of boxes, numbered from left to right 1~n, now there are 4 kinds of operations.
1 x y means move the X box to the left of the Y box.
2 x y means move the X box to the right of the Y box.
3 x y means the position of the X box and the Y box are exchanged
4 Flip all the boxes in order.
The last question is the number of boxes in odd position after m operation.
Idea: The best way to use a doubly linked list. This is simulated using an array method, using Left[i] and Right[i]
The box number for the left and right of the box numbered I, respectively (0 means no box). by simulating
The linked list method changes the connection order.
#include <iostream> #include <algorithm> #include <cstdio> #include <cstring>using namespace Std;int left[100010],right[100010];void Link (int l,int R) {right[l] = R; Left[r] = L;} int main () {int n,m,kase = 0; while (CIN >> n >> m) {for (int i = 1; I <= n; i++) {left[i] = i-1; Right[i] = (i+1)% (n+1); } right[0] = 1; Left[0] = n; int INV = 0,x,y; while (m--) {int op; Cin >> op; if (op = = 4) INV =!INV; else {cin >> X >> Y; if (op = = 3 && right[y] = = X) swap (x, y); if (OP! = 3 && Inv) op = 3-op; if (op = = 1 && X = = Left[y]) continue; if (op = = 2 && X = = Right[y]) continue; int lx,rx,ly,RY; LX = Left[x], RX = right[x], LY = Left[y], RY = Right[y]; if (op = = 1) {link (lx,rx); Link (ly,x); Link (x, y); } else if (op = = 2) {link (lx,rx); Link (y,x); Link (x,ry); } else if (op = = 3) {if (right[x] = = Y) { Link (lx,y); Link (y,x); Link (x,ry); } else {link (lx,y); Link (Y,RX); Link (ly,x); Link (x,ry); }}}} int num = 0; A long long ans = 0; for (int i = 1; I <= n; i++) {num = Right[num];if (i&1) ans + = num; } if (INV &&!) ( n&1) ans = (long Long) n (n+1)/2-ans; cout << "Case" << ++kase << ":" << ans << endl; } return 0;}
UVA12657 Boxes in a line "bidirectional linked list" "Array emulation"