当前位置:网站首页>codeforces Linova and Kingdom
codeforces Linova and Kingdom
2022-08-02 14:22:00 【先求一个导】
题目
题意: 给定以1为根的树,选择恰好k个点染黑色,其余点为白色。这k个点的幸福值为其到树根的最短路上白色点的个数,问和最大为多少。
思路: 贪心。首先深度深的叶子最优,其次就不好说了,选了父节点子节点贡献就会减少。不妨把子节点贡献减少的值交给父节点,这样总和不变,可以据此直接排序选出贡献最大的k个点。
时间复杂度: O(nlogn)
代码:
// Problem: A. Linova and Kingdom
// Contest: Codeforces - Codeforces Round #635 (Div. 1)
// URL: https://codeforces.com/problemset/problem/1336/A
// Memory Limit: 256 MB
// Time Limit: 2000 ms
//
// Powered by CP Editor (https://cpeditor.org)
#include<bits/stdc++.h>
using namespace std;
const int N = 2e5+10;
int n,m,k,T;
vector<int> va[N];
int sz[N];
int ans[N];
void dfs(int cur,int fa,int d)
{
sz[cur] = 1;
for(auto j:va[cur])
{
if(j==fa) continue;
dfs(j,cur,d+1);
sz[cur] += sz[j];
}
// if(cur==4) cout<<d<<" "<<sz[cur]<<"\n";
ans[cur] = d - sz[cur] + 1;
}
void solve()
{
cin>>n>>k;
for(int i=0;i<n-1;++i)
{
int x,y; cin>>x>>y;
va[x].push_back(y),va[y].push_back(x);
}
dfs(1,0,0);
// for(int i=1;i<=n;++i) cout<<i<<":"<<ans[i]<<"\n";
sort(ans+1,ans+n+1);
int now = n;
long long res = 0;
while(k--)
{
res += ans[now--];
}
cout<<res;
}
signed main(void)
{
solve();
return 0;
}
边栏推荐
猜你喜欢
随机推荐
解决(An error happened during template parsing (template: “class path resource [templates/...]
lammps学习(一)单晶硅纳米磨削
XML和注解(Annotation)
filebeat的配置
2022-7-15 第五组 瞒春 学习笔记
2022-07-27 第六小组 瞒春 学习笔记
Redis + Caffeine实现多级缓存
第六章-6.1-堆-6.2-维护堆的性质-6.3-建堆
JSP技术
DOM —— 事件代理
2021 Huawei Cup Mathematical Modeling Contest E question - Ultra-Wideband (UWB) precise positioning problem under signal interference
DOM - page rendering process
【网络参考模型】
Nvm,Nrm使用教程
Golang学习(三十五) go 连接redis
在命令行或者pycharm安装库时出现:ModuleNotFoundError: No module named ‘pip‘ 解决方法
【QMT】给QMT量化交易软件安装和调用第三方库(举例通达信pytdx,MyTT,含代码)
nvm详细安装步骤以及使用(window10系统)
lammps学习(二)联合原子模型聚乙烯拉伸
如何使用Swiper外部插件写一个轮播图