这道题目我做的不对。事实上,我按书上的标程抄的,几乎一模一样,我认为他没有什么错误,可我就是不知道为什么我在代码仓库下的刘汝佳写的程序就AC,我写的就WA。跳了一下午,两程序样例输出完全一样(奇怪的是和书上答案不一样)一个字一个字的比对,就是找不出哪里不一样。我觉得极少不一样的地方应该没有影响,哪位大神愿意给看看?
这是一道双向链表,同样没有用指针,而是用两个数组模拟,道理和上面的那道非指针单向链表题目一样
刘汝佳的代码
// 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() { freopen("1.txt","r",stdin); freopen("2.txt","w",stdout); 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; }
我的代码
//Boxes in a line-doubly linked list #include<cstdio> #include<algorithm> using namespace std; int left[100010],right[100010]; void linked(int l,int r){ right[l]=r;left[r]=l; } int main(){ freopen("1.txt","r",stdin); freopen("2.txt","w",stdout); int n,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);//good deal } right[0]=1;left[0]=n;//notice!!! int op,x,y,inv; 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);//all are changed!!! 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){ linked(lx,rx);linked(ly,x);linked(x,y); } else if (op==2){ linked(lx,rx);linked(y,x);linked(x,ry);//here is wrongTUT } else if (op==3){ if (right[x]==y){ linked(lx,y);linked(y,x);linked(x,ry); } else { linked(ly,x);linked(x,ry);linked(lx,y);linked(y,rx); } } } } 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; }
【日常学习】【模拟双向链表】【疑问】Uva12657 - Boxes in a Line题解
原文地址:http://blog.csdn.net/ametake/article/details/44018179