You are given a rooted tree with vertices numerated from 11 to nn. A tree is a connected graph without cycles. A rooted tree has a special vertex named root.
Ancestors of the vertex ii are all vertices on the path from the root to the vertex ii, except the vertex ii itself. The parent of the vertex ii is the nearest to the vertex ii ancestor of ii. Each vertex is a child of its parent. In the given tree the parent of the vertex ii is the vertex pipi. For the root, the value pipi is −1−1.
An example of a tree with n=8n=8, the root is vertex 55. The parent of the vertex 22 is vertex 33, the parent of the vertex 11 is vertex 55. The ancestors of the vertex 66 are vertices 44 and 55, the ancestors of the vertex 77 are vertices 88, 33 and 55
You noticed that some vertices do not respect others. In particular, if ci=1ci=1, then the vertex ii does not respect any of its ancestors, and if ci=0ci=0, it respects all of them.
You decided to delete vertices from the tree one by one. On each step you select such a non-root vertex that it does not respect its parent and none of its children respects it. If there are several such vertices, you select the one with the smallest number. When you delete this vertex vv, all children of vv become connected with the parent of vv.
An example of deletion of the vertex 77.
Once there are no vertices matching the criteria for deletion, you stop the process. Print the order in which you will delete the vertices. Note that this order is unique.
Input
The first line contains a single integer nn (1≤n≤1051≤n≤105) — the number of vertices in the tree.
The next nn lines describe the tree: the ii-th line contains two integers pipi and cici (1≤pi≤n1≤pi≤n, 0≤ci≤10≤ci≤1), where pipi is the parent of the vertex ii, and ci=0ci=0, if the vertex ii respects its parents, and ci=1ci=1, if the vertex ii does not respect any of its parents. The root of the tree has −1−1 instead of the parent index, also, ci=0ci=0 for the root. It is guaranteed that the values pipi define a rooted tree with nn vertices.
Output
In case there is at least one vertex to delete, print the only line containing the indices of the vertices you will delete in the order you delete them. Otherwise print a single integer −1−1.
题意:就是让你删除值为1并且儿子的值也都为1的节点,若有多个,先删除最小的
一开始想复杂了。。。看了题解才发现要删的节点一开始就已经定了,不会随着节点的删除而增加或减少(若删除节点a,说明节点a的节点值都为1,设节点a的父节点为b,则b的儿子变成原来的儿子加一些值为1的节点,决定一个节点会不会删除取决于该节点的值是否为1以及它是否存在值为0的节点),所以只要给值为0的节点、有值为0的儿子的节点打标以及根节点打标,其余的全部输出就好了
#include <iostream>
#include <cstdio>
#include <string>
#include <vector>
#include <iostream>
using namespace std;
const int MAX = 1e5 + 20;
int vis[MAX];
int main()
{
int n;
scanf("%d", &n);
for(int i = 1; i <= n; i++){
int p, cc;
scanf("%d%d", &p, &cc);
hach[p] = 1;
if(p == -1){
vis[i] = 1;
}
if(cc == 0){
vis[p] = 1;
vis[i] = 1;
}
}
int flag = 1;
for(int i = 1; i <= n; i++){
if(vis[i] == 0){
flag = 0;
printf("%d ", i);
}
}
if(flag){
printf("-1\n");
}
return 0;
}