【題目敘述】https://zerojudge.tw/ShowProblem?problemid=c812
【解題想法】DFS 【筆記】
#include <iostream>
#include <cstring>
#include <map>
#include <string>
#include <algorithm>
#include <set>
#include <vector>
using namespace std;
map <int, vector<pair<int, int> > > mp;
int num;
int start;
int q;
int arr[5005];
void func(int n, int last, int mini){
for (pair<int, int> p: mp[n]){
if (p.first == last){
continue;
}else{
arr[p.first] = min(p.second, mini);
func(p.first, n, min(p.second, mini));
}
}
}
int main(){
while (cin >> num >> start >> q){
mp.clear();
int a, b, c, ans = 0, maxi = 0;
for (int i = 0; i < num-1; i++){
cin >> a >> b >> c;
if (c > maxi) maxi = c;
mp[a].push_back({b, c});
mp[b].push_back({a, c});
}
func(start, num+1, maxi);
for (int i = 1; i <= num; i++){
if (i == start) continue;
if (arr[i] >= q) ans++;
}
cout << ans << "\n";
}
}
Python code (credit: Amy Chou)
提醒:Python 預設的recursion depth很小,只有1000。因此本題有三組測資會遇到RecursionError: maximum recursion depth exceeded in comparison。加上第2行 sys.setrecursionlimit(100000) 即可解決。
import sys
sys.setrecursionlimit(100000)
def dfs(now, pre, mn):
global ans
ans += 1
for (nxt, w) in g[now]:
if nxt != pre and w >= q:
dfs(nxt, now, min(mn, w))
N, Vk, q = map(int, input().split())
g = {}
for _ in range(N-1):
u, v, w = map(int, input().split())
if u in g:
g[u].append((v, w))
else:
g[u] = [(v, w)]
if v in g:
g[v].append((u, w))
else:
g[v] = [(u, w)]
ans = -1
dfs(Vk, Vk, 2e9)
print(ans)