Codeforces - The Number Games

The nation of Panel holds an annual show called The Number Games, where each district in the nation will be represented by one contestant.

The nation has n districts numbered from 1 to n, each district has exactly one path connecting it to every other district. The number of fans of a contestant from district i is equal to 2i.

This year, the president decided to reduce the costs. He wants to remove k contestants from the games. However, the districts of the removed contestants will be furious and will not allow anyone to cross through their districts.

The president wants to ensure that all remaining contestants are from districts that can be reached from one another. He also wishes to maximize the total number of fans of the participating contestants.

Which contestants should the president remove?

Input
The first line of input contains two integers n and k (1≤k<n≤106) — the number of districts in Panel, and the number of contestants the president wishes to remove, respectively.

The next n−1 lines each contains two integers a and b (1≤a,b≤n, a≠b), that describe a road that connects two different districts a and b in the nation. It is guaranteed that there is exactly one path between every two districts.

Output
Print k space-separated integers: the numbers of the districts of which the contestants should be removed, in increasing order of district number.

Examples
inputCopy
6 3
2 1
2 6
4 2
5 6
2 3
outputCopy
1 3 4
inputCopy
8 4
2 6
2 7
7 8
1 2
3 1
2 4
7 5
outputCopy
1 3 4 5


我们从去除变为留下。

因为是2^i价值,所以肯定从大到小贪心拿是正确的。

扫描二维码关注公众号,回复: 8541595 查看本文章

怎么拿呢?我们考虑从n开始,然后从n-1 -> 1依次考虑,如果留下这个,那么到已经选取的最小距离。

这一部分求最小距离,我们树上倍增即可,因为不可能存在儿子到n被选了,但是祖先没有选的情况。

之后选完暴力染色即可。


AC代码:

#pragma GCC optimize("-Ofast","-funroll-all-loops")
#include<bits/stdc++.h>
//#define int long long
using namespace std;
const int N=1e6+10;
int n,k,f[N][20],vis[N];
vector<int> g[N];
void dfs(int x,int fa){
	f[x][0]=fa;
	for(int i=1;i<=19;i++)	f[x][i]=f[f[x][i-1]][i-1];
	for(int i=0;i<g[x].size();i++){
		int to=g[x][i];	if(to==fa)	continue;
		dfs(to,x);
	}
}
inline int calc(int x){
	int res=0;
	for(int i=19;i>=0;i--)
		if(!vis[f[x][i]])	x=f[x][i],res+=(1<<i);
	return res;
}
signed main(){
	cin>>n>>k;	k=n-k-1;
	for(int i=1,a,b;i<n;i++)	
		scanf("%d %d",&a,&b),g[a].push_back(b),g[b].push_back(a);
	dfs(n,n);	vis[n]=1;
	for(int i=n-1;i>=1&&k;i--){
		if(vis[i])	continue;
		int sum=calc(i)+1;
		if(k>=sum){
			k-=sum;	int x=i;
			while(!vis[x])	vis[x]=1,x=f[x][0];
		}
	}
	for(int i=1;i<=n;i++)	if(!vis[i])	printf("%d ",i);
	return 0;
}
发布了420 篇原创文章 · 获赞 228 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_43826249/article/details/103941895
今日推荐