Evlampiy was gifted a rooted tree. The vertices of the tree are numbered from 11 to nn. Each of its vertices also has an integer aiai written on it. For each vertex ii, Evlampiy calculated cici — the number of vertices jj in the subtree of vertex ii, such that aj<aiaj<ai.
Illustration for the second example, the first integer is aiai and the integer in parentheses is cici
After the new year, Evlampiy could not remember what his gift was! He remembers the tree and the values of cici, but he completely forgot which integers aiai were written on the vertices.
Help him to restore initial integers!
Input
The first line contains an integer nn (1≤n≤2000)(1≤n≤2000) — the number of vertices in the tree.
The next nn lines contain descriptions of vertices: the ii-th line contains two integers pipi and cici (0≤pi≤n0≤pi≤n; 0≤ci≤n−10≤ci≤n−1), where pipi is the parent of vertex ii or 00 if vertex ii is root, and cici is the number of vertices jj in the subtree of vertex ii, such that aj<aiaj<ai.
It is guaranteed that the values of pipi describe a rooted tree with nn vertices.
Output
If a solution exists, in the first line print “YES”, and in the second line output nn integers aiai (1≤ai≤109)(1≤ai≤109). If there are several solutions, output any of them. One can prove that if there is a solution, then there is also a solution in which all aiai are between 11 and 109109.
If there are no solutions, print “NO”.
Examples
Input
3
2 0
0 2
2 0
Output
YES
1 2 1
Input
5
0 1
1 3
2 1
3 0
2 0
Output
YES
2 3 2 1 2
题意:给定n个点,给出每个点的父亲节点f和每个点儿子节点的值比这个点少的儿子节点的个数k。
问能否构造出这样的一个树。不能的话就输出NO,可以的话就输出YES,并且输出这个树各个点的权值。
思路:对于每个点,如果儿子节点个数少于k,就不可能构造出这样的一个树。如果可以构造出这样的一棵树,对于每一个节点的k,那么当前点在剩下点中的位置就是第k+1小,这样我们就可以用n个数去构造这一棵树。
代码如下:
#include<bits/stdc++.h>
using namespace std;
const int maxx=2e3+100;
struct edge{
int next;
int to;
}e[maxx<<1];
int nux[maxx];//记录每一个节点的比它小的个数
int head[maxx],son[maxx],ans[maxx];
vector<int> p;
int n,Top,tot;
/*--------事前准备--------*/
inline void add(int u,int v)
{
e[tot].to=v,e[tot].next=head[u],head[u]=tot++;
}
/*---------dfs---------*/
inline void dfs(int u,int &flag,int f)
{
son[u]=0;
for(int i=head[u];i!=-1;i=e[i].next)
{
int to=e[i].to;
if(to==f) continue;
dfs(to,flag,u);
son[u]+=son[to];
}
if(son[u]<nux[u]) flag=0;
son[u]+=1;
}
inline void dfs1(int u,int f)
{
ans[u]=p[nux[u]];
p.erase(p.begin()+nux[u]);
for(int i=head[u];i!=-1;i=e[i].next)
{
int to=e[i].to;
if(to==f) continue;
dfs1(to,u);
}
}
int main()
{
tot=0;
memset(head,-1,sizeof(head));
scanf("%d",&n);
int x,y;
for(int i=1;i<=n;i++)
{
scanf("%d%d",&x,&y);
nux[i]=y;
if(x==0) Top=i;
add(i,x);
add(x,i);
}
int flag=1;
dfs(Top,flag,0);
if(!flag) cout<<"NO"<<endl;
else
{
for(int i=1;i<=n;i++) p.push_back(i);
dfs1(Top,0);
cout<<"YES"<<endl;
for(int i=1;i<=n;i++) cout<<ans[i]<<" ";
cout<<endl;
}
return 0;
}
努力加油a啊,(o)/~