换根dp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | #include<iostream> #include<algorithm> #include<cstring> #include<queue> #define IOS std::ios::sync_with_stdio(0) using namespace std; #define int long long const int N=2e5+20; int n,sz[N],f[N],G[N]; vector< int > g[2*N]; void dfs1( int x, int fa){ sz[x]=1; for ( auto y:g[x]){ if (y==fa) continue ; dfs1(y,x); sz[x]+=sz[y]; } int s=0; for ( auto y:g[x]){ if (y==fa) continue ; s+=f[y]; } f[x]=s+sz[x]; } void dfs2( int x, int fa){ for ( auto y:g[x]){ if (y==fa) continue ; G[y]=G[x]+n-2*sz[y]; dfs2(y,x); } } signed main(){ int i,x,y; cin>>n; for (i=1;i<n;i++) cin>>x>>y,g[x].push_back(y),g[y].push_back(x); dfs1(1,0); G[1]=f[1]; dfs2(1,0); int ans=0; for (i=1;i<=n;i++) ans=max(ans,G[i]); cout<< ans <<endl; } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探