题目:1934. 移动小球
思路:
想了很久,即使用链表在插入和删除元素的时候比较快,但用来查找删除插入的位置的时间也太长。
看了别人的代码之后顿时开窍,用两个数组分别记录每一个球的左边和右边球的编号,这样就可以实现数组对元素的快速访问。非常高明而简单的方法!感觉有点类似于基于数组实现的双端链表。
代码:
1 #include<iostream> 2 using namespace std; 3 4 int lefts[500001]; //lefts[i] stores the lefts ball's number of the ball i. 5 int rights[500001]; //rights[i] stores the rights ball's number of the ball i. 6 7 void initial(int num_of_balls); 8 9 int main(){ 10 int testcases; 11 cin>>testcases; 12 while(testcases--){ 13 int num_of_balls,num_of_commands,choice,x,y; 14 cin>>num_of_balls>>num_of_commands; 15 initial(num_of_balls); 16 for(int i=0;i<num_of_commands;i++){ 17 cin>>choice>>x>>y; 18 //take out x,and renew the old adjacent ball of x 19 rights[lefts[x]]=rights[x]; 20 lefts[rights[x]]=lefts[x]; 21 if(choice==1){ //x is inserted y's left. 22 rights[lefts[y]]=x; 23 lefts[x]=lefts[y]; 24 lefts[y]=x; 25 rights[x]=y; 26 }else{//move x to y's right. 27 lefts[rights[y]]=x; 28 rights[x]=rights[y]; 29 rights[y]=x; 30 lefts[x]=y; 31 } 32 } 33 int position=0; 34 while(num_of_balls--){ 35 cout<<rights[position]<<' '; 36 position=rights[position]; 37 } 38 cout<<endl; 39 } 40 return 0; 41 } 42 void initial(int num_of_balls){ 43 rights[0]=1;//point to the first ball. 44 for(int i=1;i<=num_of_balls;i++){ 45 lefts[i]=i-1; 46 rights[i]=i+1; 47 } 48 }