求助大佬(#6WA)
查看原帖
求助大佬(#6WA)
490978
小超手123楼主2022/7/13 10:33

#include<bits/stdc++.h>
using namespace std;
int n,k;
vector<int>p[100005];
bool vis[100005];
int a,b; //分别记录树的直径的两端 
int num,maxn=-1;
int lj[100005];
int maxd[100005],d[100005];
int dis[100005];
bool cmp(int aa,int bb){
    return aa>bb;
}
void dfsa(int x,int s){
    if(s>maxn){
        maxn=s;
        num=x;
    }
    for(int i=0;i<p[x].size();i++){
        int y=p[x][i];
        if(vis[y]==1)continue;
        vis[y]=1;
        dfsa(y,s+1);
    }
}
void dfsb(int x,int s,int last){
    if(s>maxn){
        maxn=s;
        num=x;
        lj[last]=x;
    }
    for(int i=0;i<p[x].size();i++){
        int y=p[x][i];
        if(vis[y]==1)continue;
        vis[y]=1;
        dfsb(y,s+1,x);
    }
}
void dfsc(int x,int fa){
    maxd[x]=d[x];
    for(int i=0;i<p[x].size();i++){
        int y=p[x][i];
        if(y==fa)continue;
        d[y]=d[x]+1;
        dfsc(y,x);
        maxd[x]=max(maxd[x],maxd[y]);
    }
} 
int main(){
    cin>>n>>k;
    for(int i=1;i<=n-1;i++){
        int u,v;
        cin>>u>>v;
        p[u].push_back(v);
        p[v].push_back(u);
    }
    vis[1]=1;
    dfsa(1,0);
    maxn=-1;
    memset(vis,0,sizeof(vis));
    a=num;

    vis[a]=1;
    dfsb(a,0,0);
    b=num;
    memset(vis,0,sizeof(vis));
    int now=0;
    int opt=0;
    do{
        now=lj[now];
        if(now!=0)opt++;

    }while(now!=0);
    int root,tot=0;
    do{
        now=lj[now];
        if(now!=0)tot++;
        if(tot==(opt+1)/2){
            root=now;
            break;
        }
    }while(now!=0);
    //cout<<root<<endl;
    vis[root]=1;
    dfsc(root,0);
    for(int i=1;i<=n;i++){
        dis[i]=maxd[i]-d[i];
        //cout<<"maxd"<<"["<<i<<"]="<<maxd[i]<<" ";
        //cout<<"d"<<"["<<i<<"]="<<d[i]<<" ";
        //cout<<endl;
    }
    sort(dis+1,dis+n+1,cmp);
    cout<<dis[k+1]+1;
    return 0;
}
/*
16 5
1 2
2 3
3 4
5 3
6 1
6 7
8 6
6 9
7 10
10 12
10 13
8 11
14 1
14 15
15 16
*/
2022/7/13 10:33
加载中...