双向链表
注意:如果算法是最后处理翻转情况时,注意指令4翻转后1,2两个指令也要翻转处理;
指令3 中交换盒子要注意两个盒子相邻的情况
#include <iostream>
#include <cstring>
using namespace std; int ri[],le[]; void link (int l,int r){
ri[l]=r;le[r]=l;
} void moveleft (int l,int r){
link (le[l],ri[l]);
link (le[r],l);
link (l,r);
} void moveright (int l,int r){
link (le[l],ri[l]);
link (l,ri[r]);
link (r,l);
} void exchange (int l,int r){
int ll,rl,lr,rr;
ll=le[l];rl=ri[l];lr=le[r];rr=ri[r];
if (ll==r){
link (lr,l);link (l,r);link (r,rl);
}
else if (l==lr){
link (ll,r);link (r,l);link (l,rr);
}
else {
link (ll,r);link (r,rl);
link (lr,l);link (l,rr);
}
} int main (){
int n,m,kase=,inv;
while (cin>>n>>m){
inv=;
memset (ri,,sizeof ri);
memset (le,,sizeof le);
for (int i=;i<=n;i++)
link (i,i+);
for (int i=;i<m;i++){
int c;
cin>>c;
if (c==)
inv++;
else {
int x,y;
cin>>x>>y;
if (x==y)
continue ;
if (inv%) //经过指令4后指令1,2也要翻转处理;
c=-c;
if (c==){
moveleft (x,y);
}
else if (c==){
moveright (x,y);
}
else {
exchange (x,y);
}
}
//int temp=0;
//for (int i=ri[0];i<=n&&temp<n;i=ri[i]){
// cout<<i<<" ";
// temp++;
//}
}
long long ans=;
int f;
if (n%)
f=;
else f=inv%;
int temp=;
for (int i=ri[];i<=n&&temp<n;i=ri[i]){// cout<<ri[i]<<" ";
if (temp%==f){
ans+=i;
}
temp++;
}
cout<<"Case "<<++kase<<": ";
cout<<ans<<endl;
}
return ;
}