Submission #994698

# Submission time Handle Problem Language Result Execution time Memory
994698 2024-06-08T04:01:19 Z doducanh Torrent (COI16_torrent) C++14
100 / 100
308 ms 26008 KB
#include <bits/stdc++.h>

using namespace std;
const int maxn=3e5+7;
vector<int>adj[maxn];
int dp[maxn];
int pa[maxn];
int n,a,b;
void dfs1(int u,int par)
{
    for(int v:adj[u])if(v!=par){
        pa[v]=u;
        dfs1(v,u);
    }
}
int dfs2(int u,int par,int x,int y)
{
    vector<int>tmp;
    dp[u]=0;
    for(int v:adj[u])if(v!=par){
        if(u==x&&v==y)continue;
        if(v==x&&u==y)continue;
        dfs2(v,u,x,y);
        tmp.push_back(dp[v]);
    }
    sort(tmp.rbegin(),tmp.rend());
    for(int i=0;i<tmp.size();i++){
        dp[u]=max(dp[u],(tmp[i]+i+1));
    }
    return dp[u];
}
int delta(int x)
{
    return (dfs2(a,0,x,pa[x])-dfs2(b,0,x,pa[x]));
}
int calc(int x)
{
    return max(dfs2(a,0,x,pa[x]),dfs2(b,0,x,pa[x]));
}
main()
{
    ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
    cin>>n>>a>>b;
    for(int i=1;i<n;i++){
        int x,y;
        cin>>x>>y;
        adj[x].push_back(y);
        adj[y].push_back(x);
    }
    dfs1(a,0);
    int t=b;
    vector<int>v;
    while(t!=a){
        v.push_back(t);
        t=pa[t];
    }
//    for(int i=1;i<=n;i++)cout<<dp[i]<<"\n";
    int l=0,r=v.size()-1;
    int res=0;
    while(l<=r){
        int m=(l+r)/2;
        if(delta(v[m])>0){
            res=m;
            l=m+1;
        }
        else r=m-1;
    }
    res++;
    int sol=calc(v[res]);
//    cout<<v[res]<<" "<<pa[v[res]]<<"\n";
    if(res>0)sol=min(sol,calc(v[res-1]));
    if(res<r)sol=min(sol,calc(v[res+1]));
    if(res>1)sol=min(sol,calc(v[res-2]));
    if(res<r-1)sol=min(sol,calc(v[res+2]));
    cout<<sol;
    return 0;
}

Compilation message

torrent.cpp: In function 'int dfs2(int, int, int, int)':
torrent.cpp:27:18: warning: comparison of integer expressions of different signedness: 'int' and 'std::vector<int>::size_type' {aka 'long unsigned int'} [-Wsign-compare]
   27 |     for(int i=0;i<tmp.size();i++){
      |                 ~^~~~~~~~~~~
torrent.cpp: At global scope:
torrent.cpp:40:1: warning: ISO C++ forbids declaration of 'main' with no type [-Wreturn-type]
   40 | main()
      | ^~~~
# Verdict Execution time Memory Grader output
1 Correct 2 ms 9564 KB Output is correct
2 Correct 2 ms 9564 KB Output is correct
3 Correct 2 ms 9564 KB Output is correct
# Verdict Execution time Memory Grader output
1 Correct 212 ms 21844 KB Output is correct
2 Correct 220 ms 23604 KB Output is correct
3 Correct 262 ms 25748 KB Output is correct
4 Correct 308 ms 24840 KB Output is correct
5 Correct 222 ms 21588 KB Output is correct
6 Correct 245 ms 22188 KB Output is correct
7 Correct 255 ms 26008 KB Output is correct