fork download
  1. #include <bits/stdc++.h>
  2. #define ll long long
  3.  
  4. using namespace std;
  5.  
  6. const int MOD = 1e9 + 7;
  7.  
  8. void solve(){
  9. int n, k;
  10. cin >> n >> k;
  11.  
  12. vector<vector<int>> g(n, vector<int>());
  13.  
  14. for(int i = 1; i < n; i++){
  15. int x;
  16. cin>> x;
  17. x--;
  18. g[i].push_back(x);
  19. g[x].push_back(i);
  20. }
  21.  
  22. int s = 1, e = n - 1;
  23. int ans = n - 1;
  24. int cnt = 0;
  25. auto dfs = [&](int x, int par, int m, auto && self) -> int {
  26. int h = 1;
  27. for(auto y: g[x]){
  28. if(y != par){
  29. h = max(h, self(y, x, m, self) + 1);
  30. }
  31. }
  32. if(x == 0)return 0;
  33. if(h == m && par != 0){
  34. cnt++;
  35. return 0;
  36. }else{
  37. return h;
  38. }
  39. };
  40. while(s <= e){
  41. int mid = s + (e - s) / 2;
  42. cnt = 0;
  43. dfs(0, -1, mid, dfs);
  44. if(cnt <= k){
  45. ans = mid;
  46. e = mid - 1;
  47. }else{
  48. s = mid + 1;
  49. }
  50. }
  51. cout << ans << "\n";
  52.  
  53. }
  54.  
  55. int main(){
  56. ios_base::sync_with_stdio(false);
  57. cin.tie(nullptr);
  58.  
  59. int t = 1;
  60. cin >> t;
  61.  
  62. for(int i = 1; i <= t; i++){
  63. solve();
  64. }
  65. return 0;
  66. }
Success #stdin #stdout 0.01s 5296KB
stdin
5
5 1
1 1 2 2
5 2
1 1 2 2
6 0
1 2 3 4 5
6 1
1 2 3 4 5
4 3
1 1 1
stdout
2
1
5
3
1