北大算法分析和复杂性理论-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;
}
题意理解:复杂度允许暴力做,记不记录父亲是谁都可以,注意用指针的话别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;
}
相关文章推荐
- 算法分析与设计第一次作业
- 算法分析与复杂性理论 第一次上机 2的幂次方表示
- 算法分析与设计第一次作业
- 算法分析与设计课程作业第七周#1#2
- 二叉树、平衡二叉树相关操作算法
- Week 10算法分析作业
- 算法分析作业
- 国科大软件安全漏洞分析与发现第一次作业key1
- 算法分析与设计课程作业第三周#1
- [iuud8]数据结构算法之二叉树操作
- 二叉树的遍历算法实现、以及所有简单操作
- 【数据结构和算法分析】二叉树的遍历
- 哈尔滨理工大学软件与微电子学院软件工程专业2017学年大三上学期 算法设计与分析 期末大作业
- [Java算法分析与设计]二叉树的遍历
- 北大暑期课作业 - 对cnblog 和其他技术博客的分析,比较和展望
- 系统分析与设计_第一次作业
- 系统分析与设计——第一次作业
- 第一次大作业分析【番外——特效篇】
- 算法分析与设计课程作业第十五周#1#2#3
- 关于二叉树操作的11个算法