单向链表
题目描述
实现一个数据结构,维护一张表(最初只有一个元素 1 1 1)。需要支持下面的操作,其中 x x x 和 y y y 都是 1 1 1 到 1 0 6 10^6 106 范围内的正整数,且保证任何时间表中所有数字均不相同,操作数量不多于 1 0 5 10^5 105:
1 x y
:将元素 y y y 插入到 x x x 后面;2 x
:询问 x x x 后面的元素是什么。如果 x x x 是最后一个元素,则输出 0 0 0;3 x
:从表中删除元素 x x x 后面的那个元素,不改变其他元素的先后顺序。
输入格式
第一行一个整数 q q q 表示操作次数。
接下来 q q q 行,每行表示一次操作,操作具体间题目描述。
输出格式
对于每个操作 2,输出一个数字,用换行隔开。
样例 #1
样例输入 #1
6
1 1 99
1 99 50
1 99 75
2 99
3 75
2 1
样例输出 #1
75
99
做法一(感觉最正确但是超时,如果数据量大于1e8感觉做法二还得离散化)
#include<iostream>
using namespace std;
const int N =105005;
int e[N],ne[N],head=-1,idx;
void init(){
e[idx]=1;
ne[idx]=head;
head=idx;
idx++;
}
int find(int x){
for(int i=head;i!=-1;i=ne[i])
if(e[i]==x)return i;
}
void add(int x,int y){
e[idx]=y;
ne[idx]=ne[x];
ne[x]=idx;
idx++;
}
void move(int x){
ne[x]=ne[ne[x]];
}
int main(){
ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
int n;cin>>n;
init();
while(n--){
int op;cin>>op;
if(op==1){
int x,y;cin>>x>>y;
add(find(x),y);
}else if(op==2){
int x;cin>>x;
int t=find(x);
if(ne[t]!=-1)cout<<e[ne[t]]<<"\n";
else cout<<"0\n";
}else {
int x;cin>>x;
move(find(x));
}
}
}
做法二AC
#include<iostream>
using namespace std;
const int N =105005;
int e[N],ne[N],head=-1,idx;
void init(){
e[1]=1;
ne[1]=-1;
}
void add(int x,int y){
e[y]=y;
ne[y]=ne[x];
ne[x]=y;
}
void move(int x){
ne[x]=ne[ne[x]];
}
int main(){
ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
int n;cin>>n;
init();
while(n--){
int op;cin>>op;
if(op==1){
int x,y;cin>>x>>y;
add(x,y);
}else if(op==2){
int x;cin>>x;
if(ne[x]!=-1)cout<<e[ne[x]]<<"\n";
else cout<<"0\n";
}else {
int x;cin>>x;
move(x);
}
}
}