题目链接:http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=602&page=show_problem&problem=4395
说明:按着题中的思路敲的,本题还是有不少收获。
自己敲的代码:
<span style="font-size:18px;">#include<stdio.h> //#include<iostream>//这里不能用iostream,和right,left冲突 #include<algorithm> using namespace std; const int maxn= 100000 + 10; int left[maxn],right[maxn]; inline void link(int L, int R) { right[L] = R; left[R] = L; } int main(){ int n,m,kase=1; while(scanf("%d%d",&n,&m)!=EOF){//用cin习惯了,没有加EOF,TLE了。 for(int i=0;i<n;i++){ link(i,i+1); } left[0]=n;right[n]=0; int op,inv=0,x,y; while(m--){ scanf("%d",&op); if(op==4) {inv=!inv;continue;} scanf("%d%d",&x,&y); if(op==3 && right[y]==x) swap(x,y); if(op!=3 && inv) 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(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); } } } long long sum=0; int b=0; for(int i=1;i<=n;i++){ b=right[b]; if(i%2) sum+=b; } if(inv && n%2==0) sum=(long long)n*(n+1)/2-sum; printf("Case %d: %lld\n",kase++,sum); } return 0; } </span>
汝佳提供的代码:
// UVa12657 Boxes in a Line // Rujia Liu #include<cstdio> #include<algorithm> using namespace std; const int maxn = 100000 + 5; int n, left[maxn], right[maxn]; inline void link(int L, int R) { right[L] = R; left[R] = L; } int main() { int m, kase = 0; while(scanf("%d%d", &n, &m) == 2) { 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; while(m--) { 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; 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; long long ans = 0; for(int i = 1; i <= n; i++) { b = right[b]; if(i % 2 == 1) ans += b; } if(inv && n % 2 == 0) ans = (long long)n*(n+1)/2 - ans; printf("Case %d: %lld\n", ++kase, ans); } return 0; }