题目链接
http://vjudge.net/problem/UVALive-3902
思路
先无根树转有根树,然后可以贪心
对于深度大于k的节点,选择深度最深的节点,向上走k步走到节点A,那么将节点A作为一个新的server一定是最优解,然后删去以节点A为根的子树,继续上述过程
代码
#include <iostream>
#include <cstring>
#include <stack>
#include <vector>
#include <set>
#include <map>
#include <cmath>
#include <queue>
#include <sstream>
#include <iomanip>
#include <fstream>
#include <cstdio>
#include <cstdlib>
#include <climits>
#include <deque>
#include <bitset>
#include <algorithm>
using namespace std;
#define PI acos(-1.0)
#define LL long long
#define PII pair<int, int>
#define PLL pair<LL, LL>
#define mp make_pair
#define IN freopen("in.txt", "r", stdin)
#define OUT freopen("out.txt", "wb", stdout)
#define scan(x) scanf("%d", &x)
#define scan2(x, y) scanf("%d%d", &x, &y)
#define scan3(x, y, z) scanf("%d%d%d", &x, &y, &z)
#define sqr(x) (x) * (x)
const int maxn = 1005;
int n, s, k;
vector<int> G[maxn];
vector<int> node[maxn];
int fa[maxn], deep[maxn], vis[maxn];
void init() {
for (int i = 0; i < maxn; i++) {
G[i].clear();
node[i].clear();
}
memset(vis, 0, sizeof(vis));
}
void dfs(int u, int f, int d) {
if (G[u].size() == 1 && d > k) {
node[d].push_back(u);
}
for (int i = 0; i < G[u].size(); i++) {
int v = G[u][i];
if (v == f || v == -1) continue;
fa[v] = u;
deep[v] = d;
dfs(v, u, d + 1);
}
}
void dfs2(int u, int f, int d) {
vis[u] = 1;
for (int i = 0; i < G[u].size(); i++) {
int v = G[u][i];
if (v == f) continue;
if (d < k) {
dfs2(v, u, d + 1);
}
}
}
int solve() {
int cnt = 0;
for (int d = n - 1; d > k; d--) {
for (int i = 0; i < node[d].size(); i++) {
int u = node[d][i];
if (vis[u]) continue;
for (int j = 0; j < k; j++) {
u = fa[u];
}
cnt++;
dfs2(u, -1, 0);
}
}
return cnt;
}
int main() {
int T;
scan(T);
while (T--) {
init();
scan(n);
scan2(s, k);
for (int i = 0; i < n - 1; i++) {
int x, y;
scan2(x, y);
G[x].push_back(y);
G[y].push_back(x);
}
dfs(s, -1, 0);
printf("%d\n", solve());
}
return 0;
}