您的位置:首页 > 其它

Sicily 1934. 移动小球 解题报告

2013-11-10 20:49 183 查看
题目:1934. 移动小球

思路:

  想了很久,即使用链表在插入和删除元素的时候比较快,但用来查找删除插入的位置的时间也太长。

  看了别人的代码之后顿时开窍,用两个数组分别记录每一个球的左边和右边球的编号,这样就可以实现数组对元素的快速访问。非常高明而简单的方法!感觉有点类似于基于数组实现的双端链表。

代码:

#include<iostream>
using namespace std;

int lefts[500001]; //lefts[i] stores the lefts ball's number of the ball i.
int rights[500001]; //rights[i] stores the rights ball's number of the ball i.

void initial(int num_of_balls);

int main(){
int testcases;
cin>>testcases;
while(testcases--){
int num_of_balls,num_of_commands,choice,x,y;
cin>>num_of_balls>>num_of_commands;
initial(num_of_balls);
for(int i=0;i<num_of_commands;i++){
cin>>choice>>x>>y;
//take out x,and renew the old adjacent ball of x
rights[lefts[x]]=rights[x];
lefts[rights[x]]=lefts[x];
if(choice==1){ //x is inserted y's left.
rights[lefts[y]]=x;
lefts[x]=lefts[y];
lefts[y]=x;
rights[x]=y;
}else{//move x to y's right.
lefts[rights[y]]=x;
rights[x]=rights[y];
rights[y]=x;
lefts[x]=y;
}
}
int position=0;
while(num_of_balls--){
cout<<rights[position]<<' ';
position=rights[position];
}
cout<<endl;
}
return 0;
}
void initial(int num_of_balls){
rights[0]=1;//point to the first ball.
for(int i=1;i<=num_of_balls;i++){
lefts[i]=i-1;
rights[i]=i+1;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: