当前位置:网站首页>4279. Cartesian tree
4279. Cartesian tree
2022-07-03 07:03:00 【Ray. C.L】
Ideas :dfs Small root pile tree , Record the nodes of each layer
Code :
#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>
using namespace std;
const int N = 40;
int w[N];
vector<int> level[N];
int getmin(int l, int r){
int res = l;
for(int i = l; i <= r; i++)
if(w[res] > w[i])
res = i;
return res;
}
void dfs(int l, int r, int d){
if(l > r) return ;
int root = getmin(l,r);
level[d].push_back(w[root]);
dfs(l, root - 1, d+1);
dfs(root + 1, r, d+1);
}
int main()
{
int n;
cin >> n;
for(int i = 0; i < n; i++)
cin >> w[i];
dfs(0, n-1, 0);
for(int i = 0; level[i].size(); i++)
for(auto x : level[i])
cout << x << ' ';
return 0;
}
Ideas : Simulation building ,bfs
Code :
#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>
using namespace std;
const int N = 40;
int w[N];
int q[N];
int L[N], R[N];
int getmin(int l, int r){
int res = l;
for(int i = l; i <= r; i++)
if(w[res] > w[i])
res = i;
return res;
}
int dfs(int l, int r){
if(l > r) return -1;
int root = getmin(l,r);
L[root] = dfs(l, root - 1);
R[root] = dfs(root + 1, r);
return root;
}
void bfs(int root){
int hh = 0, tt = 0;
q[0] = root;
while(hh <= tt){
int x = q[hh++];
cout << w[x] << ' ';
if(L[x] != -1) q[++tt] = L[x];
if(R[x] != -1) q[++tt] = R[x];
}
}
int main()
{
int n;
cin >> n;
for(int i = 0; i < n; i++)
cin >> w[i];
int root = dfs(0, n-1);
bfs(root);
return 0;
}
边栏推荐
- How to migrate or replicate VMware virtual machine systems
- Crontab scheduled task
- 深度学习参数初始化(一)Xavier初始化 含代码
- Laravel frame step pit (I)
- Notes on the core knowledge of Domain Driven Design DDD
- Golang operation redis: write and read hash type data
- Basic teaching of crawler code
- Unit test framework + Test Suite
- Pytest -- write and manage test cases
- [attribute comparison] defer and async
猜你喜欢
每日刷題記錄 (十一)
Sorting out the core ideas of the pyramid principle
Operation principle of lua on C: Foundation
Winter vacation work of software engineering practice
利用C#实现Pdf转图片
Reading notes of "learn to ask questions"
EasyExcel
Pits encountered in the use of El checkbox group
How to migrate or replicate VMware virtual machine systems
These two mosquito repellent ingredients are harmful to babies. Families with babies should pay attention to choosing mosquito repellent products
随机推荐
golang操作redis:写入、读取hash类型数据
centos php7.2.24升级到php7.3
Golang operation redis: write and read kV data
Application scenarios of Catalan number
dataworks自定義函數開發環境搭建
【类和对象】深入浅出类和对象
2022-06-23 VGMP-OSPF-域間安全策略-NAT策略(更新中)
Class and object summary
[attribute comparison] defer and async
[Code] if (list! = null & list. Size() > 0) optimization, set empty judgment implementation method
Advanced API (local simulation download file)
每日刷題記錄 (十一)
Advanced API (multithreading)
Centos切换安装mysql5.7和mysql8.0
php artisan
Laravel frame step pit (I)
php artisan
php安装swoole扩展
[LeetCode]404. Sum of left leaves
Practical plug-ins in idea