sicily 1934移动小球

这道题在刘汝佳的《算法竞赛入门经典》里面有讲,之前用vector,超时!参考了别人的程序以后才AC,要注意输出语句的写法,以下是该题的算法(非原创)。

// source code of submission 733152, Zhongshan University Online Judge System //这道题解强调小球之间的相对顺序,而非绝对顺序; //我们定义了结构体node,并用left,right来表示小球i的左边和右边小球的编号。 //移动的过程分为两步:把小球X移出序列;把X重新插入序列 #include <iostream> using namespace std; struct node { int left; int right; }; int main() { int t,n,m,i,oper,b1,b2; //针对小球b1和b2进行oper操作 cin>>t; while(t--) { cin>>n>>m; struct node *ball = new node[n+6]; //动态分配内存 ball[0].right = 1; for(i = 1;i<=n;i++) ball[i].left = i - 1,ball[i].right = i + 1; for(i = 0;i<m;i++) { cin>>oper>>b1>>b2; if(oper == 1) { ball[ball[b1].left].right = ball[b1].right; //将b1移出序列 ball[ball[b1].right].left = ball[b1].left; ball[ball[b2].left].right = b1; //将b1重新插入序列 ball[b1].left = ball[b2].left; ball[b1].right = b2; //这两行不能与上两行颠倒(因为相对位置动态改变中) ball[b2].left = b1; } else if(oper == 2) { ball[ball[b1].left].right = ball[b1].right; //将b1移出序列 ball[ball[b1].right].left = ball[b1].left; ball[b1].right = ball[b2].right; //将b1重新插入序列 ball[ball[b2].right].left = b1; ball[b2].right = b1; //这两行不能与上两行颠倒 ball[b1].left = b2; } } int x = 0; for(i = 0;i<n;i++) //这里注意输出语句,不能写成x = ball[i].right { x = ball[x].right; cout<<x<<" "; } cout<<endl; } return 0; }

你可能感兴趣的:(算法,vector,struct,ini)