This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
#define ii pair<int, int>
#define X first
#define Y second
#define pb push_back
#define vi vector<int>
#define vii vector< pair<int, int> >
typedef long long ll;
using namespace std;
vi adj[300005];
vi path;
int n, a, b;
int banfrom, banto;
int dp[300005];
void dfs(int u, int p)
{
for(auto v: adj[u])
{
if(v == p) continue;
dfs(v, u);
}
}
bool findPath(int u, int p)
{
if(u == b)
{
path.pb(u);
return 1;
}
for(auto v : adj[u])
{
if(v == p) continue;
if(findPath(v, u))
{
path.pb(u);
return 1;
}
}
return 0;
}
int solve(int u, int p)
{
if(dp[u] != -1) return dp[u];
vi cand;
for(auto v : adj[u])
{
if(v == p) continue;
if((u == banfrom && v == banto) || (u == banto && v == banfrom)) continue;
cand.pb(solve(v, u));
}
sort(cand.begin(), cand.end());
reverse(cand.begin(), cand.end());
int res = 0;
for(int i = 0; i< (int) cand.size(); i++)
{
res = max(res, i+1+cand[i]);
}
return dp[u] = res;
}
int main()
{
scanf("%d %d %d", &n, &a, &b);
for(int i = 0; i< n-1; i++)
{
int u, v; scanf("%d %d", &u, &v);
adj[u].pb(v);
adj[v].pb(u);
}
dfs(1, 0);
findPath(a, 0);
reverse(path.begin(), path.end());
int L = 0, R = ((int) path.size())-2;
//for(auto x : path) printf("%d ", x);
//printf("\n");
int res = 1e9;
while(L<= R)
{
memset(dp, -1, sizeof dp);
int M = (L+R)/2;
banfrom = path[M];
banto = path[M+1];
int x = solve(a, 0);
int y = solve(b, 0);
res = min(max(x, y), res);
if(L == R) break;
if(x> y) R = M-1;
if(x< y) L = M+1;
if(x == y) break;
}
printf("%d\n", res);
return 0;
}
Compilation message (stderr)
torrent.cpp: In function 'int main()':
torrent.cpp:62:31: warning: ignoring return value of 'int scanf(const char*, ...)', declared with attribute warn_unused_result [-Wunused-result]
scanf("%d %d %d", &n, &a, &b);
^
torrent.cpp:65:35: warning: ignoring return value of 'int scanf(const char*, ...)', declared with attribute warn_unused_result [-Wunused-result]
int u, v; scanf("%d %d", &u, &v);
^
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |