1311E - Construct the Binary Tree - CodeForces Solution


brute force constructive algorithms trees *2200

Please click on ads to support us..

C++ Code:

#include<bits/stdc++.h>
using namespace std;

const int MAXN = 5005;
int t, n, d, a[MAXN], cnt[MAXN], clv, ans[MAXN];
int main () {
	ios::sync_with_stdio (false);
	cin.tie (0);
	cin >> t;
	while (t--) {
		cin >> n >> d;
		d = -d;
		for (int i = 0;i < n;i++) {
			cnt[i] = 1;
			d += i;
		} 
		if (d < 0) {
			cout << "NO" << endl;
			continue;
		}
		clv = 1;
		for (int i = n - 1;i >= 1;i--) {
			if (d == 0) break;
			else if (d <= i - clv) {
				cnt[i - d]++;
				cnt[i]--;
//				cout << "Moving level " << i << " to level " << i - d << endl;
				d = 0; 
//				cout << "Got " << d << " more depth sum" << endl;
				break;
			}
			else {
				if (clv >= i) break;
				cnt[clv]++;
				cnt[i] = 0;
				d -= i - clv;
//				cout << "Moving level " << i << " to level " << clv << endl; 
//				cout << "Got " << d << " more depth sum" << endl;
				if (cnt[clv] >= (1 << clv)) clv++;
			}
		}
		if (d > 0) {
			cout << "NO" << endl;
			continue;
		}
		cout << "YES" << endl;
		int lst = 1, cnt2 = 1;
		for (int i = 1;i < n;i++) {
			for (int j = 1;j <= cnt[i];j++) {
				ans[++cnt2] = lst;
				if (j % 2 == 0) lst--;
			}
			lst = cnt2;
		}
		for (int i = 2;i <= n;i++) {
			cout << ans[i] << " ";
		}
		cout << endl;
		for (int i = 1;i <= n;i++) cnt[i] = 0;
	}
	return 0;
}


Comments

Submit
0 Comments
More Questions

732B - Cormen --- The Best Friend Of a Man
1369A - FashionabLee
1474B - Different Divisors
1632B - Roof Construction
388A - Fox and Box Accumulation
451A - Game With Sticks
768A - Oath of the Night's Watch
156C - Cipher
545D - Queue
459B - Pashmak and Flowers
1538A - Stone Game
1454C - Sequence Transformation
165B - Burning Midnight Oil
17A - Noldbach problem
1350A - Orac and Factors
1373A - Donut Shops
26A - Almost Prime
1656E - Equal Tree Sums
1656B - Subtract Operation
1656A - Good Pairs
1367A - Short Substrings
87A - Trains
664A - Complicated GCD
1635D - Infinite Set
1462A - Favorite Sequence
1445B - Elimination
1656C - Make Equal With Mod
567A - Lineland Mail
1553A - Digits Sum
1359B - New Theatre Square