n个点的树,以点1为根,告诉你经过每一秒,某顶点上的苹果会到达哪个顶点,且已知一个顶点每同时出现两个苹果就会碰撞消失(如2得0,如3得1),求有多少个苹果能到达顶点1
bfs求点深度
1 #include <queue> 2 #include <vector> 3 #include <cstdio> 4 #include <cstring> 5 #include <algorithm> 6 using namespace std; 7 typedef long long LL; 8 typedef pair<int, int> P; 9 const int maxn = 1e5 + 10; 10 bool ans[maxn]; 11 bool vis[maxn]; 12 int n; 13 14 vector<int> G[maxn]; 15 16 int main() { 17 scanf("%d", &n); 18 for (int i = 2; i <= n; i++) { 19 int u; 20 scanf("%d", &u); 21 G[u].push_back(i); 22 } 23 queue<P> que; 24 que.push(P(1, 0)); 25 ans[0] = 1; 26 while (!que.empty()) { 27 P p = que.front(); que.pop(); 28 int v = p.first; 29 int dis = p.second; 30 for (int i = 0; i < G[v].size(); i++) { 31 int tmp = G[v][i]; 32 que.push(P(tmp, dis + 1)); 33 ans[dis + 1] ^= 1; 34 } 35 } 36 int res = 0; 37 for (int i = 0; i <= n; i++) { 38 res += ans[i]; 39 } 40 printf("%d\n", res); 41 return 0; 42 }