---
# System prepended metadata

title: j124. 3. 石窟探險
tags: [遞迴, APCS, dfs]

---

# j124. 3. 石窟探險
###### tags: `APCS` `遞迴` `dfs`

* 此題需要邊讀輸入邊尋訪

```C++
#include <bits/stdc++.h>
using namespace std;

long long int ans=0;

int traverse(){
    int n; // 一定要在這裡重新宣告，不能設全域
    cin>>n;
    if (n==-0) return 0;
    
    if (n%2==0){
        int left,right;
        left=traverse();
        right=traverse();
        if (left!=0) ans+=abs(n-left);
        if (right!=0) ans+=abs(right-n);
    }
    else if (n%2!=0){
        int left,right,mid;
        left=traverse();
        mid=traverse();
        right=traverse();
        
        if (left!=0) ans+=abs(n-left);
        if (mid!=0) ans+=abs(n-mid);
        if (right!=0) ans+=abs(n-right);
    }
    return n;
}

int main(){
    traverse();
    cout<<ans;
    return 0;
}
```