Written using the list in STL, TLE
#include<cstdio>#include<iostream>#include<cstring>#include<list>#include<algorithm>using namespace std;list<int> l;list<int>::iterator it1,it2,it3,it4,it5,it;void work(int a,int a1=1,int a2=1){ it1=find(l.begin(),l.end(),a1); it2=find(l.begin(),l.end(),a2); it3=find(l.begin(),l.end(),a2); it4=find(l.begin(),l.end(),a1); it5=find(l.begin(),l.end(),a2); if(a==1) { if(*it4++==a2) return; l.erase(it1); l.insert(it2,a1); } if(a==2) { if(*it5++==a1) return; l.erase(it1); l.insert(++it3,a1); } if(a==3) { l.insert(it2,a1); l.insert(it1,a2); l.erase(it1); l.erase(it2); } if(a==4) { l.reverse(); }}int main(){ int m,n; int kk,x,y; int kase=0; while(cin>>n>>m) { kase++; l.clear(); for(int i=1; i<=n; i++) l.push_back(i); for(int i=0;i<m;i++) { cin>>kk; if(kk==4) work(kk); else { cin>>x>>y; work(kk,x,y); } } bool flag=true; long long ans=0; for(it=l.begin(); it!=l.end(); ++it) { if(flag) { ans+=*it; } flag=!flag; } cout<<"Case "<<kase<<": "<<ans<<endl; } return 0;}
AC code, simulate the linked list with Arrays:
#include<cstdio>#include<cstring>#include<iostream>using namespace std;const int maxn = 100010;int next[maxn],prev[maxn];void unlink(int pos1){ int temp1 = prev[pos1]; int temp2 = next[pos1]; next[temp1]=temp2; prev[temp2]=temp1;}void link(int pos1,int pos2,int aa){ next[pos1]=aa; next[aa]=pos2; prev[pos2]=aa; prev[aa]=pos1;}int main(){ int n,m; int a,b,c; int kase=0; while(scanf("%d%d",&n,&m)!=EOF) { kase++; memset(next,0,sizeof(next)); memset(prev,0,sizeof(prev)); for(int i=1; i<=n; i++) { next[i]=(i+1)%(n+1); prev[i]=(i-1); } next[0]=1; prev[0]=n; bool flag=true; for(int i=0; i<m; i++) { scanf("%d",&a); if(a==1) { scanf("%d%d",&b,&c); if(b==prev[c]) continue; unlink(b); if(flag) link(prev[c],c,b); else link(c,next[c],b); } if(a==2) { scanf("%d%d",&b,&c); if(b==next[c]) continue; unlink(b); if(flag) link(c,next[c],b); else link(prev[c],c,b); } if(a==3) { scanf("%d%d",&b,&c); if(next[b]==c) { int temp1=prev[b]; int temp2=next[c]; prev[b]=c; next[c]=b; prev[c]=temp1; next[b]=temp2; next[temp1]=c; prev[temp2]=b; } else if(prev[b]==c) { int temp1=prev[c]; int temp2=next[b]; prev[c]=b; next[b]=c; prev[b]=temp1; next[c]=temp2; next[temp1]=b; prev[temp2]=c; } else { unlink(b); unlink(c); int temp1=prev[c]; int temp2=next[c]; link(prev[b],next[b],c); link(temp1,temp2,b); } } if(a==4) { flag=!flag; } } long long ans=0; if(flag) { bool flag1=true; for(int i=next[0]; i!=0; i=next[i]) { if(flag1) { ans+=i; } flag1=!flag1; } } else { bool flag1=true; for(int i=prev[0]; i!=0; i=prev[i]) { if(flag1) { ans+=i; } flag1=!flag1; } } cout<<"Case "<<kase<<": "<<ans<<endl; } return 0;}
STL is convenient, but it is indeed much slower. Be cautious when using it...