[ABC225D] Play Train
审题
现在有
- 将
x 和y 相连。 - 将
x 和y 的连接解除。 - 输出
x 所在链的长度,及其这条链中的所有元素。
方法
【手写链表】看到题目就可以想到链表,此题用手写链表是再好不过的一个选择。
思路
相连,即
代码
#include<bits/stdc++.h>
using namespace std;
const int NR = 2e5 + 5;
int n,q;
int x,y;
int a[NR];
int site,ans;
int l[NR],r[NR];
void link(int x,int y){ //连接
r[x] = y;
l[y] = x;
}
void dislink(int x,int y){ //断连
if(r[x] == y) r[x] = l[y] = 0;
else l[y] = r[x] = 0;
}
int main(){
cin >> n >> q;
while(q--){
int op;
cin >> op;
if(op == 1){
cin >> x >> y;
link(x,y);
}
else if(op == 2){
cin >> x >> y;
dislink(x,y);
}
else if(op == 3){ //输出
cin >> x;
site = x,ans = 1;
while(l[site] != 0) site = l[site]; //找到链头
x = site; //复制,因为要用两次
while(r[x] != 0){ //查找长度
ans++;
x = r[x];
}
cout << ans << " ";
while(r[site] != 0){ //输出元素
cout << site << " ";
site = r[site];
}
cout << site << endl; //输出另外一个元素,然后换行
}
}
return 0; //好习惯
}
不抄题解,从我做起!