Solution: https://codeforces.com/blog/entry/74224
#include <bits/stdc++.h> # define LL long long using namespace std; string s; int main(){ int T; scanf("%d", &T); while(T--){ int n,d; scanf("%d %d", &n, &d); int hi=n*(n-1)/2; int lo=0; int h=0; for(int i=2;i<=n;++i){ if((i&(i-1))==0) h++; lo+=h; } if(!(d>=lo && d<=hi)) {printf("NO ");continue;} printf("YES "); vector<int> parent(n+1); for(int i=2;i<=n;++i) parent[i]=i-1; vector<int> numOfCd(n+1,1); numOfCd[n]=0; int cur=hi; vector<int> checked(n+1,0); vector<int> dep(n+1); for(int i=1;i<=n;++i) dep[i]=i-1; while(cur>d){ int v=-1; for(int i=2;i<=n;++i){ if(checked[i]==1) continue; if(numOfCd[i]==0 && (v==-1 || dep[i]<dep[v])){ v=i; } } int p=-1; for(int i=1;i<=n;++i){ if(numOfCd[i]<2 && dep[i]==dep[v]-2){ p=i; } } if(p==-1){ checked[v]=1; continue; } numOfCd[parent[v]]--; numOfCd[p]++; parent[v]=p; dep[v]--; cur--; } for(int i=2;i<=n;++i){ printf("%d ", parent[i]); } printf(" "); } return 0; }