Codeforces Round #612 (Div. 2) B. Numbers on Tree

題意:

給你一棵樹, 還原樹上每個節點的價值, 首先樹上的每個節點都有一個數,代表這個節點子樹中有多少個節點的價值小於當前節點。

思路:

對於每一個節點,我們維護一個數組,然後數組中的值就是當前節點和當前節點子樹的編號, 然後數組中的下標就代表每個節點的價值。
dfs 回溯之後,我們就可以知道當前節點插入到數組的哪一個位置。
對於怎麼維護一個數組, 我們就可以用 vector 。vector 支持插入操作。

反思:

做這個題的時候, 完全沒有想到要維護一個數組。
所以就無從下手。

#include<bits/stdc++.h>
using namespace std;
#define pb push_back 
const int N = 3000;
int n,m,p,val[N],rt,ans[N];
vector<int>f[N];
vector<int> dfs(int x){
	vector<int>res;
	for (auto it: f[x]){
		vector<int>now = dfs(it);
		res.insert(res.end(), now.begin(), now.end());
	}
	if (val[x] > res.size()){
		puts("NO");
		exit(0);
	}
	res.insert(res.begin() + val[x], x);
	return res;
}
int main(){
	scanf("%d",&n);
	for (int i = 1; i <= n; ++i){
		scanf("%d%d",&p,&val[i]);
		if (p == 0) rt = i;
		f[p].pb(i);
	}
	vector<int> v = dfs(rt);
	for (int i = 0; i < n; ++i)
		ans[v[i]] = i + 1;
	printf("YES\n");		
	for (int i = 1; i <= n; ++i)
		printf("%d ",ans[i]);
	return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章