Question:
12657 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 4
kinds 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 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 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 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: 2500050000
题目大意:给你1~n盒子的顺序,给你指令1xy表示你要将x移到y的左边;2xy表示你要将x移到y的右边;3xy表示swap(x,y);4表示翻转整条链,输出指令操作后的奇数位的和
解题思路:此题用双向链表,保存每个数的左右分别是那个数字。操作4执行奇数次相当于执行了1次(此时若执行操作1则相当于执行操作2,执行操作2相当于执行操作1,把op=3-op就行了),偶数次相当于并没有执行操作4
(https://www.bnuoj.com/v3/external/126/12657.pdf)
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long LL;
const int maxn=1e5+5;
int right_[maxn],left_[maxn],n,m,ncase;
void link(int l,int r)
{
right_[l]=r;
left_[r]=l;
}
int main()
{
while(~scanf("%d%d",&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 op,x,y,inv=0;
for(int i=0;i<m;i++)
{
scanf("%d",&op);
if(op==4)
inv=!inv;
else
{
scanf("%d%d",&x,&y);
if(op==3&&right_[y]==x) //对一些特殊情况进行操作
swap(x,y);
if(op!=3&&inv) //遇到翻转奇数次则将op=3-op
op=3-op;
if(op==1&&x==left_[y]) continue;
if(op==2&&x==right_[y]) continue;
int 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 b=0;
LL ans=0;
for(int i=1;i<=n;i++)
{
b=right_[b];
if(i%2==1)
ans+=b;
}
if(inv&&n%2==0) //只有偶数位才有影响,奇数位并无影响
ans=(LL)n*(n+1)/2-ans; //总数减去
printf("Case %d: %lld\n",++ncase,ans);
}
return 0;
}
体会:链表想起来简单,但很容易错,更别说双向链表