D. Destruction of a Tree
time limit per test1 second
memory limit per test256 megabytes
You are given a tree (a graph with n vertices and n - 1 edges in which it’s possible to reach any vertex from any other vertex using only its edges).
A vertex can be destroyed if this vertex has even degree. If you destroy a vertex, all edges connected to it are also deleted.
Destroy all vertices in the given tree or determine that it is impossible.
Input
The first line contains integer n (1 ≤ n ≤ 2·105) — number of vertices in a tree.
The second line contains n integers p1, p2, …, pn (0 ≤ pi ≤ n). If pi ≠ 0 there is an edge between vertices i and pi. It is guaranteed that the given graph is a tree.
Output
If it’s possible to destroy all vertices, print “YES” (without quotes), otherwise print “NO” (without quotes).
If it’s possible to destroy all vertices, in the next n lines print the indices of the vertices in order you destroy them. If there are multiple correct answers, print any.
Examples
input
5
0 1 2 1 2
output
YES
1
2
3
5
4
input
4
0 1 2 3
output
NO
Note
In the first example at first you have to remove the vertex with index 1 (after that, the edges (1, 2) and (1, 4) are removed), then the vertex with index 2 (and edges (2, 3) and (2, 5) are removed). After that there are no edges in the tree, so you can remove remaining vertices in any order.
如果节点数是偶数个,一定不可砍,因为边数为奇数,而每次砍偶数边。
从任意节点看都是树(因此可以任意确定一个节点开始搜索),一个奇数树一定可以砍。
证明:假设是奇数树,从节点A开始遍历子树,若一个子树是奇数树,若一个子树是偶数树,则加上A到子树的边是偶数条边,即在A之前砍这个子树,若一个子树是奇数树,则先砍A,仍然是偶数条边。
如果要砍一个节点,要满足所有子树都是奇数大小的子树,如果这个子树有偶数节点,一定在回溯之前已经被砍了。
#include<bits/stdc++.h>
using namespace std;
#define N 2*100001
vector<int> eg[N];
int sta[N],n;//sta=1:以此为根的子树为奇
int deg[N];
int vis[N];
int stk[N],ini[N],sz[N];
int pt;
int cnt;
vector<int> ans;
void cut(int u);
void dfs(int u,int pre)
{
sta[u]=sz[u]=1;
if(pre!=u)deg[u]^=1;
ini[u]=pt;
stk[pt++]=u;
for(int i=0;i<eg[u].size();i++)
{
int v=eg[u][i];
//printf("v:%d\n",v);
if(v==pre)continue;
dfs(v,u);
if(sz[v])
{
deg[u]^=1;
sz[u]+=sz[v];
sta[u]&=(sz[v]&1);
}
}
if(deg[u]==0&&sta[u])cut(u);
return;
}
void cut(int u)
{
for(int i=ini[u];i<pt;i++)
{
printf("%d\n",stk[i]);
}
pt=ini[u];
sz[u]=0;
}
int main()
{
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
int tp;
scanf("%d",&tp);
if(tp)
{
eg[i].push_back(tp);
eg[tp].push_back(i);
}
}
if(!(n&1))
{
printf("NO\n");
return 0;
}
printf("YES\n");
dfs(1,1);
return 0;
}