0分,但是样例过了
查看原帖
0分,但是样例过了
539726
Xeffry楼主2023/1/9 18:05

思路跟第一篇题解一样

#include<bits/stdc++.h>
using namespace std;
struct add{
	vector<int>next;
	int ans,tree;
}pop[100005];
int n,k,bk[100005],bk2[100005],bk3[100005];
int maxx,maxd,anss,book[100005],len;
void dfs(int x,int dep){
	bk[x]=1;
	if(dep>maxd){
		maxx=x;
		maxd=dep;
	}
	for(int i=0;i<pop[x].next.size();i++){
		if(!bk[pop[x].next[i]])dfs(pop[x].next[i],dep+1);
	}
}
int maxx2;
int dfs2(int x,int dep){
	bk2[x]=1;
	int sun=dep;maxd=max(maxd,dep);
	for(int i=0;i<pop[x].next.size();i++){//cout<<pop[3].next[0]<<endl;
		if(!bk2[pop[x].next[i]])sun=max(sun,dfs2(pop[x].next[i],dep+1));
	}
	
	if(maxd==sun&&sun!=0&&dep==sun/2){
		maxx2=x;
	}
	return sun;
}
int dsa(int x,int dep){
	bk3[x]=1;
	anss+=dep;//cout<<anss<<"  "<<dep<<"   "<<x<<endl;
	pop[x].tree=1;
	for(int i=0;i<pop[x].next.size();i++){
		if(!bk3[pop[x].next[i]])pop[x].tree+=dsa(pop[x].next[i],dep+1);
	}
	len++;
	book[len]=pop[x].tree;
	return pop[x].tree;
}
int main(){
	cin>>n>>k;
	for(int i=1;i<n;i++){
		int x,y;
		cin>>x>>y;
		pop[x].next.push_back(y);
		pop[y].next.push_back(x);
	}
	dfs(1,0);
	maxd=0;
	dfs2(maxx,0);
	//*
	//cout<<maxx2<<endl;
	bk3[maxx2]=1;
	for(int i=0;i<pop[maxx2].next.size();i++){
		dsa(pop[maxx2].next[i],1);
	}
	//cout<<anss<<endl;
	sort(book+1,book+len+1);
	for(int i=0;i<=k;i++)anss-=book[len-i];
	//for(int i=1;i<=len;i++)cout<<book[i]<<" ";
	cout<<anss;
	//*/
	return 0;
}

实在不知道怎么调了。

2023/1/9 18:05
加载中...