移动盒子(Boxes in a Line)
You have n boxes in a line on the table numbered 1 . . . n from left to right. Your task is to simulate 4kinds of commands:
• 1 X Y : move box X to the left to Y (ignore this if X is already the left of Y )
• 2 X Y : move box X to the right to Y (ignore this if X is already the right of Y )
• 3 X Y : swap box X and Y
• 4: reverse the whole line.
Commands are guaranteed to be valid, i.e. X will be 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 executing2 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 will be at most 10 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 are numbered 1 to nfrom 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: 2500050000
分析:
使用双向链表,用left_[i]和right_[i]分别表示编号位i的盒子左边和右边的盒子编号(如果是0,表示不存在),通过以下过程可以将两个结点相互连接:
void link(int a, int b)
{
right_[a] = b;
left_[b] = a;
}
注意:
操作4比较特殊,为了避免一次修改所有元素的指针,此处添加一个标记flat, 表示有没有执行过操作4,(若flare = 1时,再执行一次操作4,则flat变为0)。这样,当op为1或2且flat = 1时, 只需吧op变成3-op(注意操作3不受flat的影响)即可。最终输出时根据flat的值的不同进行不同的处理。
源代码:
#include<iostream>
using namespace std;
const int maxn = 100000 + 5;
int left_[maxn], right_[maxn];
void link(int a, int b);
int main()
{
int n, m, k = 1;
int op, flat = 0;
while (scanf("%d%d", &n, &m) == 2)
{
flat = 0;
for (int i = 1; i <= n; i++)
{
left_[i] = i - 1;
right_[i] = i + 1;
}
right_[n] = 0;
right_[0] = 1;
left_[0] = n;
while(m --)
{
scanf("%d", &op);
if (op == 4) flat = !flat;
else
{
int X, Y;
scanf("%d%d", &X, &Y);
if (op != 3 && flat) op = 3 - op;
if (op == 1 && left_[Y] == X) continue;
if (op == 2 && right_[Y] == X) continue;
int LX = left_[X], RX = right_[X], LY = left_[Y], RY = right_[Y];
if (op == 1)
{
link(LX, RX);
link(X, Y);
link(LY, X);
}
else if (op == 2)
{
link(LX, RX);
link(Y, X);
link(X, RY);
}
else if (op == 3)
{
if (right_[Y] == X)
X ^= Y ^= X ^= Y;
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 b = 0;
long long ans = 0;
for (int i = 1; i <= n; i++)
{
b = right_[b];
if(i % 2 == 1)
ans += b;
}
if (n % 2 == 0 && flat == 1)
{
ans = n * (n + 1) / 2 - ans;
}
cout << "Case " << k++ << ": " << ans << endl;
}
return 0;
}
void link(int a, int b)
{
right_[a] = b;
left_[b] = a;
}