A. Almost Balanced Tree
题意:
给定
a
a
a 个权值为
1
1
1 的节点,
b
b
b 个权值为
2
2
2 的节点,构造一棵二叉树,满足两子树权值之差不超过
1
1
1,无子树权值看成
0
0
0,输出构造二叉树
思路:
贪心的想,先用
2
2
2,尽量把
2
2
2 平均放到离根节点近的位置,然后用
1
1
1 平衡使得差值不超过
1
1
1
code:
#include<bits/stdc++.h>
#define endl '\n'
#define ll long long
#define ull unsigned long long
#define ld long double
#define all(x) x.begin(), x.end()
#define mem(x, d) memset(x, d, sizeof(x))
#define eps 1e-6
using namespace std;
const int maxn = 2e6 + 9;
const int mod = 1e9 + 7;
const int inf = 0x3f3f3f3f;
const ll INF = 0x3f3f3f3f3f3f3f3f;
ll n, m;
int val[maxn], l[maxn], r[maxn];
bool f = 0;
int cnt = 0;
void dfs(int p, int a, int b){
if(b){
--b;
val[p] = 2;
}
else{
--a;
val[p] = 1;
}
int lb = b / 2, rb = b - b / 2;
int sum = a + b * 2;
int la = sum / 2 - lb * 2;// 用权值1的节点平衡两子树
int ra = a - la;
if(la < 0 || ra < 0){
f = 1;return;
}
if(la || lb){
l[p] = ++cnt;
dfs(cnt, la, lb);
}
if(ra || rb){
r[p] = ++cnt;
dfs(cnt, ra, rb);
}
}
void work()
{
cin >> n >> m;
dfs(++cnt, n, m);
if(f){
cout << -1 << endl;return;
}
for(int i = 1; i <= n + m; ++i){
cout << val[i] << " " << l[i] << " " << r[i] << endl;
}
}
int main()
{
ios::sync_with_stdio(0);
// int TT;cin>>TT;while(TT--)
work();
return 0;
}