跳到正文

题解

题解:CF1286B Numbers on Tree

kevinZ99约 4 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 4 分钟
题目
CF1286B

版本

  1. v1当前

solution

看到题,似乎像是一个构造。

所以考虑将 aa 构造为一个序列。

因为是序列,所以对于根节点有 aroot=croot+1a_{root}=c_{root}+1。

可以发现其实对于一个节点 xx,它的 aa 就是现在还没有被使用过的数中的第 cx+1c_{x}+1 小的数。

注意事项

1、若子树大小比 cc 小那么无解。

2、输出 NO 之后,记得退出程序。

code

C++
//Author:Kevin Z K Y
#include <bits/stdc++.h>
#define up(a,b,c) for(int (a)=(b);(a)<=(c);(a)++)
#define dn(a,b,c) for(int (a)=(b);(a)>=(c);(a)--)
#define fst first
#define sed second
using namespace std;
using ull = unsigned long long ;
using ll = long long ;using hint = __int128 ;
using pii = pair<int,int> ;using pll = pair<ll,ll> ;
using vi = vector<int> ;using vl = vector<ll> ;
using vpi = vector<pii> ;using vpl = vector<pll> ;
using db = double ;namespace mystl{
	#define gc() getchar()
	ll qpow(ll a,ll b,const ll&p){if (a==0ll) return 0ll; ll c=1ll;
		while(b) { if(b & 1) c=a*c%p; a=a*a%p; b>>=1; } return c; }
	template<typename T>void read(T&x) {x=0; bool f=false; char ch;
		ch = gc(); while(ch<'0'||ch>'9') f |= ( ch=='-') , ch=gc();
		while(ch>='0'&&ch<='9') x=x*10+ch-'0' , ch=gc(); x=f?-x:x;}
	template<typename T>void write(T x){char s[40];short d=0;T y=x;
		if(x<0) putchar('-'),y=-y;if(x==0){ putchar('0'); return; }
		while(y){s[++d]=y%10+'0';y/=10;}while(d>0)putchar(s[d--]);}
	template<typename T>void wris(T x,char c){write(x);putchar(c);}
}using namespace mystl;
namespace my{
	const int N=2005;
	int n;
	vi g[N];
	int c[N];
	bool vis[N];
	int root=0;
	int ans[N];
	int siz[N];
	void dfs(int x,int fa){
		int get=0,now=1,id=-1;
		while(now<=n&&get<c[x]+1){
			if(!vis[now])get++,id=now;
			if(get==c[x]+1)break;
			now++;
		}if(id==-1){
			cout<<"NO\n";
			exit(0);
		}ans[x]=id,vis[id]=true;
		siz[x]=1;
		for(int v:g[x]){
			if(v==fa)continue;
			dfs(v,x);
			siz[x]+=siz[v];
		}if(siz[x]-1<c[x]){
			cout<<"NO\n";
			exit(0);
		}
	}
	void solve(){
		cin>>n;
		up(i,1,n){
			int x;cin>>x>>c[i];
			if(x==0){
				root=i;
				continue;
			}
			g[x].push_back(i);
			g[i].push_back(x);
		}
		dfs(root,-1);
		cout<<"YES\n";
		up(i,1,n)cout<<ans[i]<<' ';
	}
}
int main(){
//  freopen("","r",stdin);
//  freopen("","w",stdout);
	ios::sync_with_stdio(false);cin.tie(nullptr);cout.tie(nullptr);
	int _=1;while(_--)my::solve();return 0;
}
原文