uva12657Boxes in a Line(双向链表)

题目链接:

lrj--p144。

 1 #include<cstring>
 2  #include<cstdio>
 3  #include<algorithm>
 4  using namespace std;
 5  const int maxn=100000+10;
 6  int l[maxn],r[maxn];
 7  int n,m;
 8  void link(int x,int y)
 9  {
10      r[x]=y;
11      l[y]=x;
12  }
13 
14  int main()
15  {
16      int s=0;
17      while(scanf("%d%d",&n,&m)==2)
18      {
19         for(int i=1;i<=n;i++)
20         {
21          l[i]=i-1;
22          r[i]=(i+1)%(n+1);
23         }
24         l[0]=n;
25         r[0]=1;
26 
27         int op,x,y;
28         int ok=0;
29 
30         for(int i=0;i<m;i++){
31         scanf("%d",&op);
32         if(op==4) ok=!ok;
33         else 
34         { 
35          scanf("%d%d",&x,&y);
36          int lx=l[x],ly=l[y],rx=r[x],ry=r[y];
37          if(x==y) continue;
38          if(ok&&(op==1||op==2)) op=3-op;
39          if(op==1)
40          {
41             if(x==ly) continue;
42             else 
43             {
44                 link(lx,rx);
45                 link(ly,x);
46                 link(x,y);
47             }
48          }
49          else if(op==2)
50          {
51              if(x==ry) continue;
52                 else 
53                 {
54                     link(lx,rx);
55                     link(y,x);
56                     link(x,ry);
57                 }
58          }
59          else if(op==3) 
60          {
61             if(rx==y)
62             {
63                 link(lx,y);
64                 link(y,x);
65                 link(x,ry);
66             }
67             else if(ry==x)
68             {
69                 link(ly,x);
70                 link(x,y);
71                 link(y,rx);
72             }
73             else 
74             {
75                 link(lx,y);
76                 link(y,rx);
77                 link(ly,x);
78                 link(x,ry);
79             }
80          }
81         }
82      }
83      long long ans=0;
84      int b=0;
85      for(int i=1;i<=n;i++){
86         b=r[b];
87         if(i%2==1) ans+=b;
88      }
89 
90 
91      if(ok&&n%2==0)  ans=(long long)(1+n)*n/2-ans;
92      printf("Case %d: %lld
",++s,ans);
93      }
94      return 0;
95  }
原文地址:https://www.cnblogs.com/yijiull/p/6612978.html