生活随笔
收集整理的這篇文章主要介紹了
codeforces1453 E. Dog Snacks
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
E. Dog Snacks
Heltion大佬題解
fuf_ufu?表示節點uuu到最近葉子節點的距離。
首先不難發現,考慮一棵子樹根節點為uuu,一定每次都把一整棵子樹上的食物吃完,然后再去別的子樹。
由于每次狗總是先去離他最近的節點,如果我們把一棵子樹的食物吃完時,一定停留在一個葉子節點上,即從葉子節點直接到另一棵子樹。
然后就是結論:
考慮每個非根非葉子結點,可以發現對其每個兒子vvv都要滿足k≥fv+2k≥f_v+2k≥fv?+2.
對于根節點,除至多一個兒子之外的每個兒子vvv都要滿足k≥fv+2k≥f_v+2k≥fv?+2而那個兒子只需滿足k≥ft+1k≥f_t+1k≥ft?+1,不難發現我們需要讓ftf_tft?越大越好,因為要么+1要么+2,顯然讓最大的+1才可能全局最可能小。
#define IO ios::sync_with_stdio(false);cin.tie();cout.tie(0)
#pragma GCC optimize(2)
#include<set>
#include<map>
#include<cmath>
#include<stack>
#include<queue>
#include<random>
#include<bitset>
#include<string>
#include<vector>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<unordered_map>
#include<unordered_set>
using namespace std
;
typedef long long ll
;
typedef pair
<int,int> pii
;
const int N
=200010,M
=2*N
;
int h
[N
],e
[M
],ne
[M
],idx
;
int n
,res
;
int f
[N
],dep
[N
],d
[N
];
void add(int a
,int b
)
{e
[idx
]=b
;ne
[idx
]=h
[a
];h
[a
]=idx
++;
}
void dfs(int u
,int fa
)
{vector
<int> w
;for(int i
=h
[u
];i
!=-1;i
=ne
[i
]){int j
=e
[i
];if(j
==fa
) continue;dfs(j
,u
);f
[u
]=min(f
[j
]+1,f
[u
]);w
.push_back(f
[j
]);}if(w
.empty()) return;sort(w
.begin(),w
.end());for(int i
=0;i
+1<w
.size();i
++) res
=max(res
,w
[i
]+2);if(u
==1) res
=max(res
,w
.back()+1);else res
=max(res
,w
.back()+2);
}
int main()
{IO
;int T
=1;cin
>>T
;while(T
--){cin
>>n
;for(int i
=1;i
<=n
;i
++) h
[i
]=-1,f
[i
]=n
+1,d
[i
]=0;idx
=res
=0;for(int i
=1;i
<n
;i
++){int a
,b
;cin
>>a
>>b
;add(a
,b
),add(b
,a
);d
[a
]++,d
[b
]++;}for(int i
=1;i
<=n
;i
++)if(d
[i
]==1) f
[i
]=0;dfs(1,-1);cout
<<res
<<'\n';}return 0;
}
總結
以上是生活随笔為你收集整理的codeforces1453 E. Dog Snacks的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。