题解
很简单的一道链表插删操作,用stl做会超时,后来自己写了个结构模拟了一下。
小技巧:这题的删除不用真删,用个布尔表mark一下就好了
ps: 还可以用树来做,中序遍历。
代码
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
using namespace std;
int n,m,ans=0;
bool cot[100001];
typedef struct PP{
int num;
struct PP* l;
struct PP* r;
} P;
int main(){
cin >> n;
int k,p;
memset(cot,false,sizeof(cot));
P* pp = (P*) malloc(sizeof(P)*(n+1));
pp[1].num = 1;
pp[1].l = pp[1].r = NULL ;
P *tmp;
for(int i=2;i<=n;i++){
pp[i].num = i;
pp[i].l = pp[i].r = NULL ;
cin>>k>>p;
// insert manipulation
if(p == 0){
if(pp[k].l == NULL){
pp[i].r = &pp[k];
pp[k].l = &pp[i];
} else{
tmp = pp[k].l;
tmp->r = &pp[i];
pp[i].l = tmp;
pp[i].r = &pp[k];
pp[k].l = &pp[i];
}
} else { // p==1
if(pp[k].r == NULL){
pp[i].l = &pp[k];
pp[k].r = &pp[i];
} else{
tmp = pp[k].r;
tmp->l = &pp[i];
pp[i].r = tmp;
pp[i].l = &pp[k];
pp[k].r = &pp[i];
}
}
}
cin>>m;
while(m--){// mark as delet
cin>>k;
cot[k] = true;
}
tmp = &pp[1];
while(tmp->l != NULL) tmp = tmp->l; // search for head
while(tmp != NULL){ // print
if( !cot[ tmp->num ] ) cout<< tmp->num <<" ";
tmp = tmp->r;
}
return 0;
}