Codeforces Round #635 (Div. 2) 比赛人数14830
[codeforces 1337C] Linova and Kingdom 公式推导
总目录详见https://blog.csdn.net/mrcrack/article/details/103564004
在线测评地址https://codeforces.com/contest/1337/problem/C
Problem | Lang | Verdict | Time | Memory |
---|---|---|---|---|
C - Linova and Kingdom | GNU C++17 | Accepted | 124 ms | 13900 KB |
手模了几组数据,发现设置工业的位置,对幸福指数的影响,与该位置的深度,该位置的子树节点数有关,
并且,当前加入工业的位置,对应的子树的节点,一定都已加入了工业。
考虑对树,自底向上研究。
以样例1为例
各个节点对应树的深度
dep[1]=1
dep[2]=2,dep[3]=2,dep[4]=2
dep[5]=3,dep[6]=3,dep[7]=3
各个节点对应子树的数量
size[1]=7
size[2]=1,size[3]=3,size[4]=2
size[5]=1,size[6]=1,size[7]=1
自底向上研究,研究加入的节点(即设置该节点为工业),导致幸福指数的变化
加入节点5,幸福指数增加2
加入节点6,幸福指数增加2
加入节点3,幸福指数:
增加了1=dep[3]-1(节点3对应的幸福指数是1=dep[3]-1),
减少了2=size[3]-1(节点5,6对应的幸福指数损失是2=size[3]-1,size[3]-1代表节点5,6的数量),
总共变化了-1=1-2=dep[3]-1-(size[3]-1)=dep[3]-size[3]
加入节点2,幸福指数增加1
加入节点4,幸福指数增加1
加入节点1,幸福指数:增加了0=dep[1]-1,减少了6=size[1]-1,
总共变化了-6=0-6=dep[1]-1-(size[1]-1)=dep[1]-size[1]
AC代码如下
#include <cstdio>
#include <algorithm>
#define maxn 200010
#define LL long long
using namespace std;
LL sum;
int dep[maxn],size[maxn],head[maxn],tot;
struct node{
int to,next;
}e[maxn<<1];
void add_edge(int u,int v){
tot++,e[tot].to=v,e[tot].next=head[u],head[u]=tot;
}
void dfs(int u,int fa){
int v,b;
size[u]=1;
for(b=head[u];b;b=e[b].next){
v=e[b].to;
if(v==fa)continue;
dep[v]=dep[u]+1;
dfs(v,u);
size[u]+=size[v];
}
}
int main(){
int n,k,i,u,v;
scanf("%d%d",&n,&k);
for(i=1;i<n;i++){
scanf("%d%d",&u,&v);
add_edge(u,v),add_edge(v,u);
}
dep[1]=1;
dfs(1,-1);
for(i=1;i<=n;i++)dep[i]=dep[i]-size[i];
sort(dep+1,dep+1+n);
for(i=n-k+1;i<=n;i++)sum+=dep[i];
printf("%lld\n",sum);
return 0;
}