P1395 会议 讲解

· · 算法·理论

设 sum_x 是节点 x 与节点 x 的子树的节点的数量之和,设节点 y_1\dots y_t 是节点 x 的儿子,设节点 u 是 x 的父亲。

具体来说,$sum_x=\sum_{i=1}^{t}sum_{y_i}$,即 $x$ 儿子的节点之和,这样递归求解即可。 又设 $dp_x$ 是当会议节点 $x$ 举行时,所有点到 $x$ 的路程之和。 分两种情况计算 $dp_x$: ![](https://cdn.luogu.com.cn/upload/image_hosting/3ffzbzq5.png) 先把 $dp_u$ 的值赋值给 $dp_x$,即现在 $dp_x$ 存的是所有节点到 $dp_u$ 的距离之和。 ①在 $x$ 子树的节点: 此时需减去 $sum_x$,因为每个 $x$ 子树的节点到 $x$ 的距离都比到 $u$ 节点少 $1$。 ②不在 $x$ 子树的节点: 首先,不在 $x$ 子树的节点数为 $n-sum_x$,即总节点数减去子树节点个数。 然后,不在 $x$ 子树的节点想到 $x$ 必须经过 $u$,又因为 $x$ 和 $u$ 的距离是 $1$,所以需要累加 $n-sum_x$。 合并后得 $dp_x=dp_u+n-2\times sum_x$。 答案为 $dp_1\dots dp_n$ 的最小值。 - 时间复杂度:$O(n)$。 - 注意事项: **如果有多个符合条件的,输出编号最小的那一个**,所以,在统计答案时需要比较编号大小。 还有,$dp_1=\sum_{i=2}^{n}sum_i$。 - 参考代码: ```cpp //#pragma GCC optimize(3) #include<cstdio> #include<vector> using namespace std; inline int read() { int x=0,f=1; char s; s=getchar(); while(s<48||s>57) { if(s=='-')f=-f; s=getchar(); } while(s>47&&s<58) { x=(x<<3)+(x<<1)+(s-48); s=getchar(); } return x*f; } constexpr int N=5e4+1; int n; vector<int> g[N]; int sum[N],dp[N]; int id=1e9,ans=1e9; int dfs(int u,int fa)//求sum数组 { int i,son; for(i=0;i<g[u].size();++i) { son=g[u][i]; if(fa==son)continue; sum[u]+=dfs(son,u); } sum[u]++; if(u>1)dp[1]+=sum[u]; return sum[u]; } int min(int x,int y) { return x<y?x:y; } void DP(int u,int fa)//求dp数组 { if(ans>dp[u]) { id=u; ans=dp[u]; } if(dp[u]==ans)id=min(id,u); int i,son; for(i=0;i<g[u].size();++i) { son=g[u][i]; if(son==fa)continue; dp[son]=dp[u]+sum[1]-(sum[son]<<1); DP(son,u); } } int main() { n=read(); int x,y,i; for(i=1;i<n;++i)//建边 { x=read(); y=read(); g[x].push_back(y); g[y].push_back(x); } dfs(1,1); DP(1,1); printf("%d %d",id,ans);//编号以及最小值 return 0; } ```