이 제출은 이전 버전의 oj.uz에서 채점하였습니다. 현재는 제출 당시와는 다른 서버에서 채점을 하기 때문에, 다시 제출하면 결과가 달라질 수도 있습니다.
#include <bits/stdc++.h>
#define ll long long
#define fi first
#define se second
#define endl '\n'
#define MASK(i) (1LL << (i))
#define ull unsigned long long
#define ld long double
#define pb push_back
#define all(x) (x).begin() , (x).end()
#define BIT(x , i) ((x >> (i)) & 1)
#define TASK "task"
#define sz(s) (int) (s).size()
using namespace std;
const int mxN = 5e5 + 227;
const int inf = 1e9 + 277;
const int mod = 24211007;
const ll infll = 1e18 + 7;
const int base = 200;
const int LOG = 29;
template <typename T1, typename T2> bool minimize(T1 &a, T2 b) {
if (a > b) {a = b; return true;} return false;
}
template <typename T1, typename T2> bool maximize(T1 &a, T2 b) {
if (a < b) {a = b; return true;} return false;
}
int n;
int a, b;
vector<int> adj[mxN];
int par[mxN];
int dp1[mxN];
int dp2[mxN];
int res = inf;
void dfs(int u, int p)
{
for(int v : adj[u]) {
if(v == p) continue;
par[v] = u;
dfs(v, u);
}
}
void calc_dp1(int u, int p, int x)
{
vector<int> val;
for(int v : adj[u]) {
if(v == p || v == x) continue;
calc_dp1(v, u, x);
val.pb(dp1[v]);
}
sort(all(val));
reverse(all(val));
int cnt = 0;
for(auto it : val) {
++cnt;
maximize(dp1[u], it + cnt);
}
}
void calc_dp2(int u, int p, int x)
{
vector<int> val;
for(int v : adj[u]) {
if(u == x && v == par[u]) continue;
if(v == p) continue;
calc_dp2(v, u, x);
val.pb(dp2[v]);
}
sort(all(val));
reverse(all(val));
int cnt = 0;
for(auto it : val) {
++cnt;
maximize(dp2[u], it + cnt);
}
}
void calc(int x)
{
for(int i = 1; i <= n; i++) dp1[i] = dp2[i] = 0;
calc_dp1(a, -1, x);
calc_dp2(b, -1, x);
// cout << x << ' ' << dp1[a] << ' ' << dp2[b] << endl;
minimize(res, max(dp1[a], dp2[b]));
}
void solve()
{
cin >> n >> a >> b;
for(int i = 1; i < n; i++) {
int u, v;
cin >> u >> v;
adj[u].pb(v);
adj[v].pb(u);
}
dfs(a, -1);
int x = b;
vector<int> pos;
while(x != a) {
pos.pb(x);
x = par[x];
}
int lo = 1, hi = sz(pos);
while(lo + 1 < hi) {
int mid = (lo + hi) / 2;
calc(pos[mid - 1]);
if(dp1[a] > dp1[b]) lo = mid;
else hi = mid;
}
calc(pos[lo - 1]);
calc(pos[hi - 1]);
lo = 1, hi = sz(pos);
while(lo + 1 < hi) {
int mid = (lo + hi) / 2;
calc(pos[mid - 1]);
if(dp1[a] < dp1[b]) lo = mid;
else hi = mid;
}
calc(pos[lo - 1]);
calc(pos[hi - 1]);
cout << res;
}
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
//freopen(TASK".in" , "r" , stdin);
//freopen(TASK".out" , "w" , stdout);
int tc = 1;
// cin >> tc;
while(tc--) {
solve();
}
return 0;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |