首页 > 编程语言 > 详细

算法入门经典P146(双向链表)

时间:2021-07-20 15:37:47      阅读:21      评论:0      收藏:0      [点我收藏+]
#include<cstdio>
const int maxn = 100005;
int n,left[maxn],right[maxn];
void link(int L,int R){
    right[L] = R;
    left[R] = L;
}
void swap(int&X,int&Y){
    int t = X;
    X = Y;
    Y = t;
}
int main(){
    int m,op,X,Y,kase=0,b;
    long long ans;
    bool inv;
    while(scanf("%d%d",&n,&m)==2){
        right[0] = 1;
        left[n] = 0;
        for(int i=1;i<=n;i++){
            left[i] = i-1;
            right[i] = (i+1)%(n+1);
        }
        inv = false;
        for(int i=0;i<m;i++){
            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);
            }
            if(op==2){
                link(LX,RX);link(Y,X);link(X,RY);
            }
            if(op==3){
                if(left[Y]==X){link(LX,Y);link(Y,X);link(X,RY);}
                else{
                    link(LX,Y);link(Y,RX);link(LY,X);link(X,RY);
                }
            }
            b = 0;
            ans = 0;
        }
        b = 0;
        ans = 0;
        for(int j=1;j<=n;j++){
            b = right[b];
            if(j%2==1)ans+=b;
        }
        if(inv)ans = (long long)n*(n+1)/2-ans;
        printf("Case %d:%lld\n",++kase,ans);
    }
    return 0;
} 

 

算法入门经典P146(双向链表)

原文:https://www.cnblogs.com/stevenzrx/p/15033354.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!