您的位置:首页 > 理论基础 > 数据结构算法

北大算法分析和复杂性理论-2017算法课第一次作业E:二叉树的操作

2017-09-14 21:59 344 查看
http://algorithm.openjudge.cn/algorithma/E/

题意理解:复杂度允许暴力做,记不记录父亲是谁都可以,注意用指针的话别re。

急转弯:无

算法:无

数据结构:二叉树(的遍历)

#include <iostream>
#include <cstdio>
#include <cstring>

using namespace std;

const int maxn = 100 + 10;

struct node{
int id, lson, rson, fa;
};
node t[maxn];
int n, m;

int getl(int u) {
if(t[u].lson == -1) return u;
return getl(t[u].lson);
}

int main() {
int T;
scanf("%d", &T);
for(int _ = 0; _ < T; _++) {
scanf("%d%d", &n, &m);
memset(t, 0, sizeof(t));
for(int i = 0; i < n; i++){
int x, y, z;
scanf("%d%d%d", &x, &y, &z);
t[x].lson = y;
t[x].rson = z;
t[z].fa = x;
t[y].fa = x;
}
for(int i = 0; i < m; i++) {
int type, x, y;
scanf("%d", &type);
if(type == 1) {
scanf("%d%d", &x, &y);
int xfa = t[x].fa, yfa = t[y].fa;
t[x].fa = yfa;
t[y].fa = xfa;
int *xpos;
int *ypos;
if(t[xfa].lson == x) {
xpos = &t[xfa].lson;
} else{
xpos = &t[xfa].rson;
}
if(t[yfa].lson == y) {
ypos = &t[yfa].lson;
} else{
ypos = &t[yfa].rson;
}
int tx = (*xpos), ty = (*ypos);
(*xpos) = ty;
(*ypos) = tx;
} else{
scanf("%d", &x);
printf("%d\n", getl(x));
}
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息