cf1179D
cf1179D
链接
思路
csdn
很玄学,正解是斜率优化dp,但被一个奇妙的贪心过了。
代码
#include <bits/stdc++.h>
#define ll long long
using namespace std;
const int _=5e5+7;
int n,siz[_],S,id;
ll f[_],ans;
vector<int> G[_];
void dfs1(int u,int fa) {
siz[u]=1;
for(auto v:G[u]) {
if(v==fa) continue;
dfs1(v,u),siz[u]+=siz[v];
}
}
void dfs2(int u,int fa) {
for(auto v:G[u]) {
if(v==fa) continue;
f[v]=f[u]+1LL*(siz[u]-siz[v])*siz[v];
dfs2(v,u);
}
if(f[u]>f[id]) id=u;
}
int main() {
scanf("%d",&n);
for(int i=1,u,v;i<n;++i) {
scanf("%d%d",&u,&v);
G[u].push_back(v),G[v].push_back(u);
}
S=1;
f[1]=0,dfs1(S,0),dfs2(S,0);
memset(siz,0,sizeof(siz));
memset(f,0,sizeof(f));
S=id;
f[1]=0,dfs1(S,0),dfs2(S,0);
ans=1LL*n*(n-1)/2+f[id];
cout<<ans<<"\n";
return 0;
}