meaning of the title
You have a row of boxes, numbered 1, 2, 3, from left to right. n. The following four instructions can be executed:
1 X Y means moving box X to the left of box Y (ignore this instruction if X is already on the left of box Y).
2 X Y means moving box X to the right of box Y (ignore this instruction if X is already on the right of box Y).
3 X Y denotes the position of the exchange boxes X and Y.
4 means reversing the whole chain.
thinking
Two way linked list
Each operation only needs to modify the element pointing in the list.
In addition, if the program has been inverting the entire chain, if it has been operating, it must be very complex.
Because the title only requires the sum of all odd position labels, when box num is odd, the reverse order of the box has no effect.
If boxnum is even, it will have an effect, and then it can be judged concretely. So the inversion chain operation can be marked with bool.
AC code
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
typedef long long ULL;
const int maxn = 100000 + 10;
int l[maxn],r[maxn];
void link( int left, int right ){
r[left] = right;
l[right] = left;
}
int main()
{
int boxnum, casenum, i;
int x, a, b, num = 0;
ULL result;
bool ok;
while( ~scanf("%d%d",&boxnum, &casenum) ){
for( i = 1; i <= boxnum; i++ ){
l[i] = i - 1;
r[i] = ( i + 1 ) % ( boxnum + 1 );
}
l[0] = boxnum;
r[0] = 1;
ok = false;
while( casenum-- ){
scanf("%d",&x);
if( x == 4 ){ //Reversal
ok = !ok;
continue;
}
scanf("%d%d",&a,&b);
if( x == 3 && r[b] == a ) swap(a,b);
if( x != 3 && ok ) x = 3 - x;
if( (x == 1 && l[b] == a) || (x == 2 && r[b] == a) ) continue;
int la = l[a], ra = r[a], lb = l[b], rb = r[b];
if( x == 1 ){
link(la, ra);
link(a, b);
link(lb, a);
}
else if( x == 2 ){
link(la, ra);
link(b, a);
link(a, rb);
}
else if( x == 3 ){
if( ra == b ){
link(la, b);
link(b, a);
link(a, rb);
}
else{
link(la, b);
link(b, ra);
link(lb, a);
link(a, rb);
}
}
}
int t = 0;
result = 0;
for( int i = 1; i <= boxnum; i++ ){
t = r[t];
if( i % 2 != 0 ) result += t;
}
if( ok && boxnum % 2 == 0 )
result = (ULL)boxnum*(boxnum+1)/2 - result;
//cout << boxnum*(boxnum+1)/2 ;
printf("Case %d: %llu\n",++num, result);
}
return 0;
}