社区讨论
WA on #29,跪求大佬帮助 π π
P5536【XR-3】核心城市参与者 1已保存回复 0
讨论操作
快速查看讨论及其快照的属性,并进行相关操作。
- 当前回复
- 0 条
- 当前快照
- 1 份
- 快照标识符
- @m3d0ubze
- 此快照首次捕获于
- 2024/11/11 20:50 去年
- 此快照最后确认于
- 2025/11/04 14:53 4 个月前
CPP
#include <bits/stdc++.h>
using namespace std;
const int maxn=1e5+10;
int n,k,cnt,root;
struct edge
{
int to,nxt;
}e[maxn<<1];
int head[maxn],deep[maxn],mxdep[maxn],ans[maxn],f[maxn],numson[maxn];
struct node
{
int deep,id;
bool operator < (const node &p) const
{
return this->deep<p.deep;
}
}tmp[maxn];
void add (int u,int v)
{
cnt++;
e[cnt].to=v;
e[cnt].nxt=head[u];
numson[u]++;
head[u]=cnt;
}
void dfs (int x,int fa)
{
f[x]=fa;
mxdep[x]=deep[x]=deep[fa]+1;
for (int i=head[x];i;i=e[i].nxt) {
int son=e[i].to;
if (son==fa) continue;
dfs(son,x);
mxdep[x]=max(mxdep[x],mxdep[son]);
}
}
void dfs2 (int x,int fa)
{
mxdep[x]=deep[x]=deep[fa]+1;
for (int i=head[x];i;i=e[i].nxt) {
int son=e[i].to;
if (son==fa) continue;
dfs2(son,x);
mxdep[x]=max(mxdep[x],mxdep[son]);
}
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
cin>>n>>k;
for (int i=1;i<n;i++) {
int u,v;
cin>>u>>v;
add(u,v); add(v,u);
}
// cout<<"The edge are as below: "<<endl;
// for (int kk=1;kk<=n;kk++) {
// for (int i=head[kk];i;i=e[i].nxt)
// cout<<e[i].to<<" ";
// cout<<endl;
// }
// 注意1不应该是叶子节点
for (int i=1;i<=n;i++)
if (numson[i]>1) {
root=i;
// cout<<"root is "<<root<<endl;
dfs(i,0);
break;
}
// cout<<"The deep are as below"<<endl;
// for (int i=1;i<=n;i++)
// cout<<deep[i]<<" "<<mxdep[i]<<endl;
int mx1=0,mx2=0;
for (int i=head[root];i;i=e[i].nxt) {
if (mx1<=mxdep[e[i].to]) {
mx2=mx1;
mx1=mxdep[e[i].to];
}
else if (mx2==0) mx2=mxdep[e[i].to];
}
for (int i=1;i<=n;i++) {
tmp[i].deep=deep[i];
tmp[i].id=i;
}
sort(tmp+1,tmp+1+n);
int length=mx1+mx2-1;
root=tmp[n].id;
// cout<<"length is "<<length<<endl;
for (int kk=1;kk<=length/2;kk++)
root=f[root];
memset(deep,0,sizeof(deep));
// cout<<"root is "<<root<<endl;
dfs2(root,0);
// for (int i=1;i<=n;i++) cout<<deep[i]<<" "<<mxdep[i]<<endl;
for (int i=1;i<=n;i++)
ans[i]=mxdep[i]-deep[i];
sort(ans+1,ans+1+n);
cout<<ans[n-k]+1;
return 0;
}
/*
12 2
1 2
1 3
3 4
3 5
5 6
5 7
5 8
7 9
7 10
10 11
10 12
*/
回复
共 0 条回复,欢迎继续交流。
正在加载回复...