CF1490D-Permutation Transformation
CF1490D-Permutation Transformation
题目大意
给你一个长度为 \(n\) 的排列 \(p\) 。最大值为深度为 \(0\) 的点。左边为左子树,右边为右子树。子树中最大值的点则为深度为 \(1\) 的点。以此类推,直到子树为空。
询问是,每一个数字,对应的深度。
题解
直接暴力 \(dfs\) ,每次找到区间内最大值的位置,最大值左边为左子树,右边为右子树,直接模拟即可。
#include<bits/stdc++.h>
#define ios ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define umap unordered_map
#define endl '\n'
using namespace std;
using i128 = __int128;
const int mod =1e9+7;
template <typename T>void read(T&x){
x=0;int f = 1;
char c=getchar();
for(;!isdigit(c);c=getchar())if(c=='-')f=-1;
for(;isdigit(c);c=getchar())x=(x<<1)+(x<<3)+(c^48);
x*=f;
}
template <typename T>void print(T x) {
if (x < 0) { putchar('-'); x = -x; }
if (x > 9) print(x / 10);
putchar(x % 10 + '0');
}
#define int long long
const int N=500005;
const int M=2000005;
int a[105],d[105];
void dfs(int l,int r,int dep)
{
if(l>r) return;
int maxn=-1,maxpoi;
for(int i=l;i<=r;i++)
{
if(a[i]>maxn)
{
maxn=a[i];
maxpoi=i;
}
}
d[maxpoi]=dep;
dfs(l,maxpoi-1,dep+1);
dfs(maxpoi+1,r,dep+1);
}
inline void solve()
{
int n;
cin>>n;
for(int i=1;i<=n;i++) cin>>a[i];
dfs(1,n,0);
for(int i=1;i<=n;i++) cout<<d[i]<<" ";
cout<<endl;
}
signed main()
{
ios;
int T=1;
cin>>T;
for(;T--;) solve();
return 0;
}

浙公网安备 33010602011771号