#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e6 + 7;
vector<int> g[maxn];
int par[maxn];
int in[maxn], out[maxn];
bool remain[maxn];
struct BIT
{
int n, c[maxn];
void init(int _n) {
n = _n;
memset(c, 0, (n + 2) << 2);
}
void update(int p, int d) {
for(int i = p;i <= n;i += i & -i) c[i] += d;
}
int query(int p) {
int res = 0;
for(int i = p;i > 0;i -= i & -i) res += c[i];
return res;
}
}bit;
int time_tag;
void dfs(int u, int fa, int d)
{
par[u] = fa;
in[u] = ++time_tag;
bit.update(in[u], d);
bit.update(in[u]+1, -d);
for(int i = 0;i < g[u].size();i ++) {
int to = g[u][i];
if(to != fa) dfs(to, u, d + 1);
}
out[u] = time_tag;
}
int main()
{
int n, k;
scanf("%d %d", &n, &k);
bit.init(n);
for(int i = 1;i < n;i ++) {
int a, b;
scanf("%d%d",&a,&b);
g[a].push_back(b);
g[b].push_back(a);
}
dfs(n,0,1);
for(int rem=0,i = n;i >= 1;i --) {
if(remain[i]) continue;
int t = bit.query(in[i]);
if(t + rem <= n - k) {
for(int j = i;!remain[j] && j;j = par[j]) {
remain[j] = 1;
rem ++;
bit.update(in[j], -1);
bit.update(out[j]+1,1);
}
}
}
for(int i = 1;i <= n;i ++) if(!remain[i]) printf("%d ",i);
return 0;
}
题目链接: http://codeforces.com/contest/980/problem/E
E. 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
.
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?
The first line of input contains two integers n
) — 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 bin the nation. It is guaranteed that there is exactly one path between every two districts.
Print k
space-separated integers: the numbers of the districts of which the contestants should be removed, in increasing order of district number.
6 3 2 1 2 6 4 2 5 6 2 3
1 3 4
8 4 2 6 2 7 7 8 1 2 3 1 2 4 7 5
1 3 4 5
In the first sample, the maximum possible total number of fans is 22+25+26=100
. We can achieve it by removing the contestants of the districts 1, 3, and 4.
题意:给出一颗N个节点的树,第i个节点的权值为2^i, 现在你必须删除K个节点(K < N),并且保证剩下的点都联通的情况下,使得剩下的点权值最大。
题解:用树状数组,维护这个点到根的路径上有几个需要保留点。