D51 树的直径 [AGC001C] Shorten Diameter
视频链接:D51 树的直径 [AGC001C] Shorten Diameter_哔哩哔哩_bilibili
[AGC001C] Shorten Diameter - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)
// 树的直径+逆向思维 #include <iostream> #include <cstring> #include <algorithm> using namespace std; #define N 2005 int head[N],to[N<<1],ne[N<<1],idx; void add(int x,int y){ to[++idx]=y;ne[idx]=head[x];head[x]=idx; } int n,k,tot,ans; void dfs(int x,int fa,int step){ tot++; //记录节点数 if(step==0) return; for(int i=head[x];i;i=ne[i]){ int y=to[i]; if(y==fa)continue; dfs(y,x,step-1); } } int main(){ scanf("%d%d",&n,&k); for(int i=1,u,v;i<n;i++){ scanf("%d%d",&u,&v); add(u,v);add(v,u); } if(k%2==0){ //k为偶数 for(int x=1;x<=n;x++){ tot=0; dfs(x,0,k/2); //以x为中心扩展 ans=max(ans,tot); } } else{ //k为奇数 for(int x=1;x<=n;x++){ for(int i=head[x];i;i=ne[i]){ tot=0; int y=to[i]; dfs(y,x,k/2); dfs(x,y,k/2); //以x,y为中心扩展 ans=max(ans,tot); } } } printf("%d\n",n-ans); }
分类:
D 图论
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
2023-09-18 C33 线段树+贪心 P1937 [USACO10MAR] Barn Allocation G
2023-09-18 C32 线段树+贪心 P1607 [USACO09FEB] Fair Shuttle G