Be sure to note that swap (x, y), X, y may be adjacent!
#include <cstdio>#defineN 100005#definell Long LongintN, M;structnode{intL, R; Node (): L (0), R (0) {} node (intL_,intr_): L (L_), R (r_) {}}num[n];voidinit () { for(inti =0; I <= n +1; i++) NUM[I].L= i-1, NUM[I].R = i +1;}voidMove2left (intXinty) { if(NUM[Y].L = = x)return ; intL, R; L= NUM[X].L, R =NUM[X].R; NUM[L].R= r, Num[r].l =l; L= NUM[Y].L, R =y; NUM[X].R= r, Num[x].l =l; NUM[L].R= x, NUM[R].L =x;}voidMove2right (intXinty) { if(NUM[Y].R = = x)return ; intL, R; L= NUM[X].L, R =NUM[X].R; NUM[L].R= r, Num[r].l =l; L= y, R =NUM[Y].R; NUM[X].R= r, Num[x].l =l; NUM[L].R= x, NUM[R].L =x;}voidSwap (intXinty) { intxl, XR, yl, yr; if(NUM[X].R = =y) {XL= Num[x].l, yr =NUM[Y].R; NUM[XL].R= y, num[yr].l =x; NUM[Y].L= XL, NUM[Y].R =x; NUM[X].L= y, NUM[X].R =yr; } Else if(NUM[X].L = =y) {XR= NUM[X].R, yl =NUM[Y].L; NUM[XR].L= y, NUM[YL].R =x; NUM[Y].L= x, NUM[Y].R =XR; NUM[X].L= YL, NUM[X].R =y; } Else{XL= num[x].l, XR =NUM[X].R; YL= Num[y].l, yr =NUM[Y].R; NUM[XL].R= y, num[xr].l =y; NUM[YL].R= x, NUM[YR].L =x; NUM[X].L= YL, NUM[X].R =yr; NUM[Y].L= XL, NUM[Y].R =XR; }}intMain () {//freopen ("OUT.txt", "w", stdout); intCases =0; while(~SCANF ("%d%d", &n, &m)) {cases++; Init (); intOP, res =1; for(inti =1; I <= m; i++) {scanf ("%d", &op); intx, y; if(Op <4) scanf ("%d%d", &x, &y); if(OP = =1&& res) | | (OP = =2&&!res)) Move2left (x, y); Else if(OP = =2&& res) | | (OP = =1&&!res)) Move2right (x, y); Else if(OP = =3) Swap (x, y); Elseres =!Res; } ll sum=0; if(res) {intt = num[0].R, C =0; while(C <N) {c++; ifC2==1) Sum + =(LL) t; //printf ("%d***\n", t);t =NUM[T].R; } } Else { intt = num[n +1].L, C =0; //printf ("%d***\n", t); while(C <N) {c++; ifC2==1) Sum + =(LL) t; //printf ("%d***\n", t);t =NUM[T].L; }} printf ("Case %d:%lld\n", cases, sum); } return 0;}
UVA 12657 (doubly linked list)