1. 程式人生 > >Codeforces 931D Peculiar apple-tree(dfs+思維).cpp

Codeforces 931D Peculiar apple-tree(dfs+思維).cpp

str () target 是我 ces spa HR lan span

題目鏈接:http://codeforces.com/contest/931/problem/D

題目大意:給你一顆樹,每個節點都會長蘋果,然後每一秒鐘,蘋果往下滾一個。兩個兩個會抵消蘋果。問最後在根節點能收到多少個蘋果。

解題思路:昨天是我想復雜了,其實就是統計下每層的蘋果數,若是奇數則答案+1。因為最終這些蘋果都會滾落匯聚到根節點,所以在滾落過程中肯定會碰撞並相消無論蘋果是怎麽分布的。

代碼:

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<vector>
 5
#include<algorithm> 6 using namespace std; 7 const int N=1e5+5; 8 9 int dep_num[N]; 10 vector<int>v[N]; 11 12 void dfs(int u,int dep){ 13 dep_num[dep]++; 14 for(int i=0;i<v[u].size();i++){ 15 int t=v[u][i]; 16 dfs(t,dep+1); 17 } 18 } 19 20
int main(){ 21 int n; 22 scanf("%d",&n); 23 for(int i=2;i<=n;i++){ 24 int fa; 25 scanf("%d",&fa); 26 v[fa].push_back(i); 27 } 28 dfs(1,1); 29 int ans=0; 30 for(int i=0;i<N;i++){ 31 ans+=dep_num[i]%2; 32 } 33 printf("
%d\n",ans); 34 return 0; 35 }

Codeforces 931D Peculiar apple-tree(dfs+思維).cpp